我的 gson 有奇怪的问题(我的 gson 版本是 2.3.1) 我有一个名为 jsonObject (JsonObject jsonObject) 的 JsonObject 实例 jsonObject 有值,不为空 我创建了另一个 JsonObject tempOject = jsonObject; 所以,当我尝试删除 tempObject 中的元素时,可以说, tempObject.remove(" children ");
然后该代码影响了 jsonObject 实例。
这是代码片段:
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);
}
我看过gson JsonObject 类,它使用深拷贝方法。这不应该影响引用,因为 JsonObject 使用深度值复制,所以返回的 JsonObject 对象是新对象。
但为什么会这样呢?
无论如何...JsonObject 类中有 deepCopy 方法
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;
}
但那是在 JsonObject 上实现的 JsonElement 类的抽象方法,并且属性未设置为公共(public),因此我无法调用该方法。但我想当我进行实例复制时,应该会直接调用该方法。
那怎么样?
提前致谢
最佳答案
这可以用来复制任何类型的任何对象! 只需要使用 Gson。
public <T> T deepCopy(T object, Class<T> type) {
try {
Gson gson = new Gson();
return gson.fromJson(gson.toJson(object, type), type);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
在您的情况下,您可以这样调用它:
JsonObject jsonObject = deepCopy(oldJsonObject, JsonObject.class);
关于java - Gson JsonObject 复制值影响其他 JsonObject 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29786197/