User 类的域如下
private String username;
private String password;
Product product;
然后
User user = new User("nan", "123");
Product product = new Product("apple", "red", 4.5);
user.setProduct(product);
String jsonStr = JSONObject.toJSONString(user);
System.out.println(jsonStr);
User u2 = JSONObject.parseObject(jsonStr, User.class);
System.out.println(u2);
结果:
{"password":"123","product":{"desc":"red","name":"apple","price":4.5},"username":"nan"} Exception in thread "main" com.alibaba.fastjson.JSONException: default constructor not found. class nan.obj.Product at com.alibaba.fastjson.util.JavaBeanInfo.build(JavaBeanInfo.java:242) at com.alibaba.fastjson.util.JavaBeanInfo.build(JavaBeanInfo.java:140) at com.alibaba.fastjson.parser.ParserConfig.createJavaBeanDeserializer(ParserConfig.java:583) at com.alibaba.fastjson.parser.ParserConfig.getDeserializer(ParserConfig.java:500) at com.alibaba.fastjson.parser.ParserConfig.getDeserializer(ParserConfig.java:357) at com.alibaba.fastjson.parser.deserializer.FastjsonASMDeserializer_1_User.deserialze(Unknown Source) at com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer.deserialze(JavaBeanDeserializer.java:208) at com.alibaba.fastjson.parser.DefaultJSONParser.parseObject(DefaultJSONParser.java:642) at com.alibaba.fastjson.JSON.parseObject(JSON.java:350) at com.alibaba.fastjson.JSON.parseObject(JSON.java:254) at com.alibaba.fastjson.JSON.parseObject(JSON.java:467) at run.App2.main(App2.java:30)
Process finished with exit code 1
发现 parseObject 出错,确实,因为 Product 类型 JSONObject 不知道
那么像这种域是自定义类的,序列化和反序列化如何做啊?
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.