一旦我将一个JSON字符串解析成GSON提供的JsonObject类(假设我不想将它解析成任何有意义的数据对象,但严格地说我想使用JsonObject),我如何能够直接修改一个键的字段/值呢?
我看不到能帮到我的API。
https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/JsonObject.html
发布于 2012-07-12 10:01:04
奇怪的是,答案是不断添加回来的属性。我还以为会有一个setter
方法。:S
System.out.println("Before: " + obj.get("DebugLogId")); // original "02352"
obj.addProperty("DebugLogId", "YYY");
System.out.println("After: " + obj.get("DebugLogId")); // now "YYY"
发布于 2016-11-10 15:33:16
这适用于使用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"
},
}
发布于 2014-10-01 21:40:31
从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"));
https://stackoverflow.com/questions/11443928
复制相似问题