Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I clone an org.json.JSONObject in Java?

Is there a way to clone an instance of org.json.JSONObject without stringifying it and reparsing the result?

A shallow copy would be acceptable.

like image 336
Daniel Schaffer Avatar asked Oct 09 '12 23:10

Daniel Schaffer


People also ask

How do I copy one JSON object to another JSON object?

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.

What is the difference between org JSON JSONObject and org JSON simple JSONObject?

simple package contains important classes like JSONValue, JSONObject, JSONArray, JsonString and JsonNumber. We need to install the json-simple. jar file to execute a JSON program whereas org. json library has classes to parse JSON for Java.


2 Answers

Easiest (and incredibly slow and inefficient) way to do it

JSONObject clone = new JSONObject(original.toString()); 
like image 66
Jaytjuh Avatar answered Sep 20 '22 16:09

Jaytjuh


Use the public JSONObject(JSONObject jo, java.lang.String[] names) constructor and the public static java.lang.String[] getNames(JSONObject jo) method.

JSONObject copy = new JSONObject(original, JSONObject.getNames(original)); 
like image 41
Bill the Lizard Avatar answered Sep 19 '22 16:09

Bill the Lizard