json-lib net.sf.ezmorph.bean.MorphDynaBean cannot be cast to xxx

阅读更多

在使用json-lib 反序列化时,报错:

Exception in thread "main" java.lang.ClassCastException: net.sf.ezmorph.bean.MorphDynaBean cannot be cast to com.jn.json.bean.Student

at com.jn.test.Test2.test_reserialize(Test2.java:104)

at com.jn.test.Test2.main(Test2.java:110)

 

项目结构如下(源代码见附件):
json-lib net.sf.ezmorph.bean.MorphDynaBean cannot be cast to xxx_第1张图片
 依赖的库如下:
json-lib net.sf.ezmorph.bean.MorphDynaBean cannot be cast to xxx_第2张图片

json-lib-2.1-jdk15.jar


 测试代码如下:把字符串转化为java对象

public static void test_reserialize(){
//		String jsonInput="{\"className\":\"计算机0705\",\"count\":0,\"students\":[{\"addrr\":null,\"age\":0,\"hobby\":\"\",\"name\":\"\"}]}";
		String jsonInput="{\"classAttribute\":{\"pp1\":\"vv1\",\"pp2\":\"vv2\"},\"className\":\"计算机0705\",\"count\":0,\"students\":[{\"addrr\":null,\"age\":0,\"attribute\":{\"p2\":\"v2\",\"p1\":\"v1\"},\"hobby\":\"\",\"name\":\"\"}]}";
		JSONObject js = JSONObject.fromObject(jsonInput);
		Class2 one = (Class2) JSONObject.toBean(js, Class2.class);
		System.out.println(one.getClassName());
		Map attribute =one.getStudents().get(0).getAttribute();
		System.out.println(attribute);
		
	}
	
	public static void main(String[] args) {
		test_reserialize();
	}

 运行时报错:

 

解决方法:

使用JsonConfig,修改后的代码如下:

public static void test_reserialize(){

		String jsonInput="{\"classAttribute\":{\"pp1\":\"vv1\",\"pp2\":\"vv2\"},\"className\":\"计算机0705\",\"count\":0,\"students\":[{\"addrr\":null,\"age\":0,\"attribute\":{\"p2\":\"v2\",\"p1\":\"v1\"},\"hobby\":\"\",\"name\":\"\"}]}";
		JSONObject js = JSONObject.fromObject(jsonInput);
		
		JsonConfig jsonConfig = new JsonConfig();

		jsonConfig.setRootClass(Class2.class);
		Map classMap = new HashMap();
		classMap.put("students", Student.class); // 指定JsonRpcRequest的request字段的内部类型
		jsonConfig.setClassMap(classMap);
		
		
		
		Class2 one = (Class2) JSONObject.toBean(js, jsonConfig);
		System.out.println(one.getClassName());
		Map attribute =one.getStudents().get(0).getAttribute();
		System.out.println(attribute);
		
	}
	

 主要增加了:

JsonConfig jsonConfig = new JsonConfig();

 

jsonConfig.setRootClass(Class2.class);

Map classMap = new HashMap();

classMap.put("students", Student.class); // 指定JsonRpcRequest的request字段的内部类型

jsonConfig.setClassMap(classMap);

 

参考:

http://www.iamcoder.net/tag/java-2/

上述代码所在项目见附件json_lib_demo2.zip

 

 

  • json-lib net.sf.ezmorph.bean.MorphDynaBean cannot be cast to xxx_第3张图片
  • 大小: 17 KB
  • json-lib net.sf.ezmorph.bean.MorphDynaBean cannot be cast to xxx_第4张图片
  • 大小: 14.4 KB
  • json-lib net.sf.ezmorph.bean.MorphDynaBean cannot be cast to xxx_第5张图片
  • 大小: 32.9 KB
  • json_lib_demo2.zip (7.8 KB)
  • 下载次数: 46
  • 查看图片附件

你可能感兴趣的:(json-lib,JsonConfig,MorphDynaBean,反序列化)