JSONObject Not Serializable?

ぃ、小莉子 提交于 2019-12-05 02:22:59

Dude, it's JSON. Why not just serialize it as JSON, instead of as a Java object of type JSONObject?

For example:

String myJsonObjectSerialized = myJsonObject.toString();

In the case you'd still want Java built-in serialization without having to resort to marshal your JSON object into string notation, one thing you could do is extend JSONObject and JSONArray from org.json and just implement Serializable.

Then you can use your own versions of JSONObject and JSONArray across the board instead of the originals.

Make sure you define all constructors on your subclasses and call their super() counterparts as well as implement specific methods that return the parent types such as getJSONObject() and getJSONArray() from properties.

If you have JSONArray inside Serializable object class try to initialize JSONArray in this way.

private transient JSONArray jsonArray;

public class Person implements Serializable {   

     private String name;  
     private transient JSONArray jsonArray;

     public String getName() {  
          return name;  
     }  

    public void setName(String name) {  
          this.name = name;  
     }

    public JSONArray getJsonArray() {  
          return jsonArray;  
     }  

    public void setJsonArray(JSONArray jsonArray) {  
          this.jsonArray = jsonArray;  
     }  

 }

Another way is to swap org.json library with json-simple.

The JSONObject class from json-simple extends HashMap which is java Serializable as well as more java-ish API.

Maven dependency:

http://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1.1

Example usage:

https://www.mkyong.com/java/json-simple-example-read-and-write-json/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!