如何直接修改JsonObject / JsonArray的值?

2022-09-01 01:19:58

一旦我将JSON字符串解析为GSON提供的JsonObject类,(假设我不希望将其解析为任何有意义的数据对象,但严格希望使用JsonObject),我如何能够直接修改键的字段/值?

我没有看到可能对我有帮助的 API。

https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/JsonObject.html


答案 1

奇怪的是,答案是继续添加回属性。我半信半疑地期待一种方法。:Ssetter

System.out.println("Before: " + obj.get("DebugLogId")); // original "02352"

obj.addProperty("DebugLogId", "YYY");

System.out.println("After: " + obj.get("DebugLogId")); // now "YYY"

答案 2

这适用于使用 修改子键值。导入使用的是JSONObject

import org.json.JSONObject;

ex json:(将 json 文件转换为字符串,同时作为输入提供)

{
    "parentkey1": "name",
    "parentkey2": {
     "childkey": "test"
    },
}

法典

JSONObject jObject  = new JSONObject(String jsoninputfileasstring);
jObject.getJSONObject("parentkey2").put("childkey","data1");
System.out.println(jObject);

输出:

{
    "parentkey1": "name",
    "parentkey2": {
     "childkey": "data1"
    },
}