如何向net.sf.json.JSONObject存入并取出自定义类实例,解决类转换异常
net.sf.json存储自定义类实例后取出报错的解决方法
错误原因
调用JSONObject.put()方法传入自定义类实例时,net.sf.json不会直接存储原始对象,会自动将自定义实例序列化为net.sf.json.JSONObject类型的结构,因此调用get()方法取出的结果本身就是JSONObject对象,无法直接强转为自定义的CustomerClass类型。
前置要求
自定义类CustomerClass需要满足两个序列化规则:
- 存在public修饰的无参构造方法
- 所有需要序列化、反序列化的属性都提供public修饰的getter、setter方法
修正后代码
import net.sf.json.JSONObject; class Test { JSONObject test = new JSONObject(); CustomerClass obj = new CustomerClass(); test.put("objInstance", obj); // 先取出序列化后的JSONObject,再通过toBean方法转为自定义类实例 JSONObject objJson = (JSONObject) test.get("objInstance"); CustomerClass retrievedInstance = (CustomerClass) JSONObject.toBean(objJson, CustomerClass.class); }
注:原有代码中new JSONObject漏写了括号,属于语法错误,实际运行也需要修正。
内容的提问来源于stack exchange,提问作者Enola Holmes
相关产品推荐
相关产品推荐

