一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

JSON字符串转换object错误:MorphDynaBean cannot be cast to com.softright.bean.TestBean

时间:2022-06-29 02:38:48 编辑:袖梨 来源:一聚教程网

错误:MorphDynaBean cannot be cast to com.softright.bean.TestBean

 


解决方法:


在JSONObject.toBean的时候

如果转换的类中有集合,可以先定义Map classMap = new HashMap();

在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 bMap = new HashMap(); 
bMap.put("key1", b1); 
A a1 = new A(bMap); 

JSONObject jsonObject = JSONObject.fromObject(a1); 
String json = jsonObject.toString(); 
jsonObject = JSONObject.fromObject(json); 

Map classMap = new HashMap(); 
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 bMap = new HashMap(); 
public A() {} 
public A(Map bMap) { 
this.bMap = bMap; 

public Map getbMap() { 
return bMap; 

public void setbMap(Map 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; 

热门栏目