json-lib net.sf.ezmorph.bean.MorphDynaBean cannot be cast to xxx
程序员文章站
2022-03-14 23:29:34
...
在使用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);
参考:
http://www.iamcoder.net/tag/java-2/
上述代码所在项目见附件json_lib_demo2.zip
下一篇: python怎么安装运行
推荐阅读
-
java.util.LinkedHashMap cannot be cast to xxx
-
java后台接收json数据,报错com.alibaba.fastjson.JSONObject cannot be cast to xxx
-
整合SSH java.lang.ClassCastException: xxx_$$_javassist_0 cannot be cast to javassist.util.proxy.Proxy
-
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to xxx 类型转换异常
-
java.util.LinkedHashMap cannot be cast to xxx
-
java后台接收json数据,报错com.alibaba.fastjson.JSONObject cannot be cast to xxx
-
json-lib net.sf.ezmorph.bean.MorphDynaBean cannot be cast to xxx
-
json-lib net.sf.ezmorph.bean.MorphDynaBean cannot be cast to xxx