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

Oh *_*oon 28 java json gson

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

我没有看到可以帮助我的API.

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

Oh *_*oon 62

奇怪的是,答案是继续追加财产.我有一半期待一种setter方法.:S

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

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

System.out.println("After: " + obj.get("DebugLogId")); // now "YYY"
Run Code Online (Sandbox Code Playgroud)

  • 他们应该称之为putProperty.会更清楚.它也没有在文档中说明这取代现有属性,但我想它不会是有效的Json. (3认同)

小智 11

这适用于修改childkey值JSONObject.导入使用的是

import org.json.JSONObject;
Run Code Online (Sandbox Code Playgroud)

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

{
    "parentkey1": "name",
    "parentkey2": {
     "childkey": "test"
    },
}
Run Code Online (Sandbox Code Playgroud)

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

输出:

{
    "parentkey1": "name",
    "parentkey2": {
     "childkey": "data1"
    },
}
Run Code Online (Sandbox Code Playgroud)

  • 只是想强调这个问题是关于 com.google.gson.JsonObject 而不是 org.json.JSONObject。底部的选定和最受好评的答案似乎是正确的 (2认同)

小智 5

从2.3版本的Gson库开始,JsonArray类有一个'set'方法.

这是一个简单的例子:

JsonArray array = new JsonArray();
array.add(new JsonPrimitive("Red"));
array.add(new JsonPrimitive("Green"));
array.add(new JsonPrimitive("Blue"));

array.remove(2);
array.set(0, new JsonPrimitive("Yelow"));
Run Code Online (Sandbox Code Playgroud)