gpt4 book ai didi

Java简单json不替换属性的值

转载 作者:行者123 更新时间:2023-11-30 01:45:44 24 4
gpt4 key购买 nike

正如上面的标题所述,我试图将“name”的值替换为“abc”,但这似乎并没有覆盖它,因为它是相同的值使用 Simple Json 替换它后java代码。

这是我的java代码:

    String jsonString = 
"{"
+ "\"data\":"
+ "["
+ "{"
+ "\"jazz\":\"black\","
+ "\"name\":\"white\","
+ "\"given\":\"red\","
+ "\"sam\":\"blue\","
+ "\"mail\":\"yellow\","
+ "\"member\":\"green\","
+ "\"department\":\"green\","
+ "\"title\":\"green\""
+ "}"
+ "]"
+ "}";
JSONParser parser = new JSONParser();
JSONObject jsonObj = (JSONObject) parser.parse(jsonString);
JSONObject newJSON = new JSONObject();

jsonObj.remove("name");
jsonObj.put("name", "abc");

正如我所说,上面的代码似乎没有对 json 结构中已有的“name”属性执行任何操作。上面的输出如下所示:

{
"data": [
{
"given": "red",
"mail": "yellow",
"jazz": "black",
"name": "white",
"member": "green",
"department": "green",
"title": "green",
"sam": "blue"
}
],
"name": "abc"
}

输出应该是什么样的:

{
"data": [
{
"given": "red",
"mail": "yellow",
"jazz": "black",
"name": "abc",
"member": "green",
"department": "green",
"title": "green",
"sam": "blue"
}
]
}

知道为什么不改变它吗?

更新1

enter image description here

最佳答案

这对我有用:

JSONArray jsonArray = (JSONArray)jsonObj.get("data");
JSONObject jsonObject = ((JSONObject)(jsonArray).get(0));
jsonObject.put("name", "abc");
System.out.println(jsonObj.toJSONString());

关于Java简单json不替换属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58066837/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com