I have a strange problem with gson (my version of gson is 2.3.1) I have an instance of JsonObject called jsonObject (JsonObject jsonObject) jsonObject is value, not empty And I create another one, JsonObject tempOject = jsonObject; Therefore, when I try to delete an element inside tempObject, let's say tempObject.remove ("children");
This code then affected the jsonObject instance.
Here is the code snippet:
jsonObject = element.getAsJsonObject();
JsonElement tempElement = element;
JsonObject tempObject = jsonObject;
String tempJson;
if(tempObject.has("children")){
tempObject.remove("children");
tempJson = tempObject.toString();
tempElement = new JsonParser().parse(tempJson);
}
if(nodes.isEmpty()){
elements = new ArrayList<>();
nodes.put(iterator, elements);
}
if(!nodes.containsKey(iterator)){
elements = new ArrayList<>();
nodes.put(iterator, elements);
}
nodes.get(iterator).add(tempElement);
if (jsonObject.has("children")){
tempNextJson = jsonObject.get("children").toString();
tempCurrJson = jsonObject.toString();
tempIterator++;
metaDataProcessor(tempNextJson, tempCurrJson, tempNextJson, tempIterator, maxLevel);
}
I read the gson JsonObject class, it uses a deep copy method. This should not affect the link, because JsonObject uses a deep copy of the value, so the returned JsonObject is new.
But why did this happen?
Anyway ... there is a deepCopy method inside the JsonObject class
JsonObject deepCopy() {
JsonObject result = new JsonObject();
Iterator i$ = this.members.entrySet().iterator();
while(i$.hasNext()) {
Entry entry = (Entry)i$.next();
result.add((String)entry.getKey(), ((JsonElement)entry.getValue()).deepCopy());
}
return result;
}
JsonElement, JsonObject, , . , , .
?