JSON字符串轉換object錯誤:MorphDynaBean cannot be cast to com.softright.bean.TestBean,類中有集合類型的屬性 因為JSONObject.toBean()把JSON字符串轉換為一個自己定義的類,當其中屬性有類似List , Map ,ArrayList的時候,麻煩就來了
錯誤:MorphDynaBean cannot be cast to com.softright.bean.TestBean
解決方法:
在JSONObject.toBean的時候
如果轉換的類中有集合,可以先定義Map<String, Class> classMap = new HashMap<String, Class>();
在classMap中put你要轉換的類中的集合名,像:classMap.put("data", StoDataInfo.class);
當然也可以put一個集合類("data",Map.class)
然後在toBean()的時候把參數加上, 像:ShenTongInfo stInfo=(ShenTongInfo) JSONObject.toBean(o, ShenTongInfo.class, classMap);
具體實例
public class JsonConvertorDemo {
public static void main(String[] args) {
B b1 = new B("b1");
Map<String, B> bMap = new HashMap<String, B>();
bMap.put("key1", b1);
A a1 = new A(bMap);
JSONObject jsonObject = JSONObject.fromObject(a1);
String json = jsonObject.toString();
jsonObject = JSONObject.fromObject(json);
Map<String, Class> classMap = new HashMap<String, Class>();
classMap.put("bMap", Map.class);
a1 = (A) JSONObject.toBean(jsonObject, A.class, classMap);
bMap = a1.getbMap();
System.out.println(bMap.get("key1").getB1());
}
}
public class A {
private Map<String, B> bMap = new HashMap<String, B>();
public A() {}
public A(Map<String, B> bMap) {
this.bMap = bMap;
}
public Map<String, B> getbMap() {
return bMap;
}
public void setbMap(Map<String, B> bMap) {
this.bMap = bMap;
}
}
public class B {
private String b1;
public B() {}
public B(String b1) {
this.b1 = b1;
}
public String getB1() {
return b1;
}
public void setB1(String b1) {
this.b1 = b1;
}
}