How to serialize JSON object in java

后端 未结 4 1430
一向
一向 2020-12-06 19:24

Hi I am using Voldemort to store my data. My key is a word and values are number of occurrence of the word and the URL. For example:

key :question
value: 10,         


        
相关标签:
4条回答
  • 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.

    0 讨论(0)
  • 2020-12-06 19:56

    Late answer, but I was searching for this myself and I have found a solution. Just to clarify, my problem was that my class contained a org.json.JSONobject, and it couldn't be serialized, which is a necessary step to pass objects in Android Bundle objects.

    1. Add the keyword transient to the field.
    2. Provide the functions writeObject and readObject for the serializer to call. This looks like an override function, but actually isn't decorated with @Override.

    Like this:

    private void writeObject(ObjectOutputStream oos) throws IOException{
        oos.defaultWriteObject();
        oos.writeChars(_jsonObject.toString());
    }
    
    private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
        ois.defaultReadObject();
        loadJSON(ois.readUTF());
    }
    

    3. In the loadJSON function, you call the JSONObject constructor that takes a string, and assign it to the transient field.

    I found this to be far easier than replacing the library.

    0 讨论(0)
  • 2020-12-06 20:10

    Have a look at Gson library. It does nice JSON to object mapping and serialization.

    0 讨论(0)
  • 2020-12-06 20:17

    Use the .toString() method of JSONObject to get the text.

    0 讨论(0)
提交回复
热议问题