在使用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()); Mapattribute =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); MapclassMap = 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.put("students", Student.class); // 指定JsonRpcRequest的request字段的内部类型
jsonConfig.setClassMap(classMap);
参考:
http://www.iamcoder.net/tag/java-2/
上述代码所在项目见附件json_lib_demo2.zip