在使用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-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<String, Object> 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<String, Class> classMap = new HashMap<String, Class>();
- classMap.put("students", Student.class); // 指定JsonRpcRequest的request字段的内部类型
- jsonConfig.setClassMap(classMap);
- Class2 one = (Class2) JSONObject.toBean(js, jsonConfig);
- System.out.println(one.getClassName());
- Map<String, Object> attribute =one.getStudents().get(0).getAttribute();
- System.out.println(attribute);
- }
主要增加了:
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setRootClass(Class2.class);
Map<String, Class> classMap = new HashMap<String, Class>();
classMap.put("students", Student.class); // 指定JsonRpcRequest的request字段的内部类型
jsonConfig.setClassMap(classMap);