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 不知道
那么像这种域是自定义类的,序列化和反序列化如何做啊?
1
blindpirate 2017-07-27 07:19:54 +08:00
default constructor not found
|