3

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.

davidalayachew
  • 1,279
  • 1
  • 11
  • 22

1 Answers1

4

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.");}
davidalayachew
  • 1,279
  • 1
  • 11
  • 22