Search code examples
javajsoncopyjson-lib

How to copy all the values from one JSONObject to another?


I understand that it's perfectly possible to copy each individual component over one by one, but it's extremely messy to do and rather ugly. Isn't there a simpler way to copy all the values from one JSONObject to another? Important to note, I am using json-lib. I'm not opposed to switching tools if it's absolutely necessary. Point is, this is a rather inefficient way of doing things.


Solution

  • After hours of searching, I finally found the answer. I'm sort of embarrased that it's this simple.

    ~

    Json-lib has a beautiful feature that allows you to take your current JSONObject and parse the entirety of the JSONObject into a String. And there already exists a method to build a JSONObject from a String. Therefore, all you need to do is turn the JSONObject into a String, and then back into a JSONObject. You could store the string as a variable (or use it as a return value), then simply take your preexisting JSONObject reference and use the method to rebuild the JSONObject from the String. Simple as that.

    EDIT - thought I would give a quick code example

    JSONObject a = /* pretend a has 100 elements inside */
    String temp = a.toString();
    JSONObject b = JSONObject.fromObject(temp);
    String temp2= b.toString();
    if(temp.equals(temp2)){System.out.println("Well done.");}
    

    EDIT 2 -- Coming back 5 years later (and with much more experience), I realize that I had inadvertently stumbled on the concept of Serialization and Deserialization.

    Serialization is the process of taking a complex data object (in this case, my JSONObject) and turning it into a basic String. That String still contains all of the bits needed to create a new JSONObject, but it is a simple String, and sending a String value over the internet, or saving it to a file -- these are things I know how to do easily, even as a beginner programmer.

    Deserialization is the process of taking that serialized value (the String I created above) and turning that back into my data object -- in this case, my JSONObject. Now, please note -- I am lucky that doing toString() is an easy way to serialize my JSONObject. However, if you want to properly serialize most other objects, toString() likely won't be enough. There are many different ways to do it, but they all depend on what type of data object you have. To find out how to serialize or deserialize your data object, you should try searching "How to serialize/deserialize <YOUR_DATA_TYPE>".