当前位置:编程学习 > JSP >>

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

错误: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; 

补充:Jsp教程,Jsp/Servlet开发工具
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,