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

For Android developers, the simplest solution without using .getNames is:

JSONObject copy = new JSONObject();
for (Object key : original.keySet()) {
  Object value = original.get(key);
  copy.put(key, value);
}

Note: This is a only a shallow copy


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));

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

JSONObject clone = new JSONObject(original.toString());

Cause $JSONObject.getNames(original) not accessible in android, you can do it with:

public JSONObject shallowCopy(JSONObject original) {
    JSONObject copy = new JSONObject();

    for ( Iterator<String> iterator = original.keys(); iterator.hasNext(); ) {
        String      key     = iterator.next();
        JSONObject  value   = original.optJSONObject(key);

        try {
            copy.put(key, value);
        } catch ( JSONException e ) {
            //TODO process exception
        }
    }

    return copy;
}

But remember it is not deep copy.