Gson JsonObject复制值影响了其他JsonObject实例

use*_*361 5 java gson

我有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);
        }
Run Code Online (Sandbox Code Playgroud)

我已经阅读了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;
}
Run Code Online (Sandbox Code Playgroud)

但那是JsonElement类中的一个抽象方法,它在JsonObject上实现,而且属性没有设置为public,所以我无法调用该方法.但我想这个方法应该在我进行实例复制时直接调用.

那个怎么样?

提前致谢

Muh*_*ifi 12

这可以用来复制任何类型的任何对象!只需要使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)

在你的情况下你可以这样称呼它:

JsonObject jsonObject = deepCopy(oldJsonObject, JsonObject.class);
Run Code Online (Sandbox Code Playgroud)


Jaa*_*koK 5

从2.8.2版开始,deepCopy()Gson JsonElement是公开的,因此您现在可以使用它制作JSON对象的深层副本。