Gibt es eine Möglichkeit, eine Instanz von org.json.JSONObject
zu klonen, ohne sie zu stringifizieren und das Ergebnis erneut zu analysieren?
Eine flache Kopie wäre akzeptabel.
Verwenden Sie den Konstruktor public JSONObject(JSONObject jo, Java.lang.String[] names)
und die public static Java.lang.String[] getNames(JSONObject jo)
-Methode.
JSONObject copy = new JSONObject(original, JSONObject.getNames(original));
Einfachste (und unglaublich langsame und ineffiziente) Methode
JSONObject clone = new JSONObject(original.toString());
Es wurde keine tiefe Klonmethode für com.google.gwt.json.client.JSONObject gefunden. Die Implementierung sollte jedoch aus wenigen Codezeilen bestehen.
public static JSONValue deepClone(JSONValue jsonValue){
JSONString string = jsonValue.isString();
if (string != null){return new JSONString(string.stringValue());}
JSONBoolean aBoolean = jsonValue.isBoolean();
if (aBoolean != null){return JSONBoolean.getInstance(aBoolean.booleanValue());}
JSONNull aNull = jsonValue.isNull();
if (aNull != null){return JSONNull.getInstance();}
JSONNumber number = jsonValue.isNumber();
if (number!=null){return new JSONNumber(number.doubleValue());}
JSONObject jsonObject = jsonValue.isObject();
if (jsonObject!=null){
JSONObject clonedObject = new JSONObject();
for (String key : jsonObject.keySet()){
clonedObject.put(key, deepClone(jsonObject.get(key)));
}
return clonedObject;
}
JSONArray array = jsonValue.isArray();
if (array != null){
JSONArray clonedArray = new JSONArray();
for (int i=0 ; i < array.size() ; ++i){
clonedArray.set(i, deepClone(array.get(i)));
}
return clonedArray;
}
throw new IllegalStateException();
}
* Hinweis: * Ich habe es noch nicht getestet!
Für Android Entwickler die einfachste Lösung ohne .getNames
ist:
JSONObject copy = new JSONObject();
for (Object key : original.keySet()) {
Object value = original.get(key);
copy.put(key, value);
}
Hinweis: Dies ist nur eine flache Kopie
Ursache $JSONObject.getNames(original)
ist in Android nicht verfügbar. Sie können dies mit
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;
}
Aber denken Sie daran, es ist keine tiefe Kopie.