gpt4 book ai didi

java - 更新 json 数组文件中的值

转载 作者:行者123 更新时间:2023-12-02 03:52:25 24 4
gpt4 key购买 nike

我正在读取一个包含 json 数组的 json 文件,并且尝试更新 jason 数组中所有对象中的一些键值,并将新更新的 json 数组写入另一个文件。

其中包含以下 json 数组的文件:

 [
{
"info": "old text"
"sometext": "old text",
"Id": 2,
"No": 12,
},
{
"info": "old text"
"sometext": "old text",
"Id": 68,
"No": 22,
},
{
"info": "old text"
"sometext": "old text",
"Id": 87,
"No": 15,
}

]

我想更新 json 数组中所有对象中的 info 和 sometext 键的值,以便使用更新的 json 数组输出到新文件(这是我想要的输出,我想通过我的代码):

 [
{
"info": "new text"
"sometext": "new text",
"Id": 2,
"No": 12,
},
{
"info": "new text"
"sometext": "new text",
"Id": 68,
"No": 22,
},
{
"info": "new text"
"sometext": "new text",
"Id": 87,
"No": 15,
}

]

这是我到目前为止的代码:

final String JSON_PATH = "old.json";
final String JSON_PATH1 = "new.json";

BufferedWriter bw = new BufferedWriter(new FileWriter(JSON_PATH1));
BufferedReader br = new BufferedReader(new FileReader(JSON_PATH));
JsonParser parser = new JsonParser();
JsonArray arrayObj = parser.parse(br).getAsJsonArray();


for(int i=0; i < arrayObj.size();i++) {
JsonObject burObj = arrayObj.get(i).getAsJsonObject();
String old_info = burObj.get("info").getAsString();
String old_sometext = burObj.get("sometext").getAsString();
burObj.addProperty(NewTextGen(old_info), "info");
burObj.addProperty(NewTextGen(old_sometext), "sometext");
burObj.remove(old_info);
burObj.remove(old_sometext);
Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
gson.toJson(arrayObj, new JsonWriter(bw));
}

when I run this code I get gibberish output of both new and old values and not my desired output.

乱码输出:

 [
{
"info": "old text"
"sometext": "old text",
"info": "new text"
"sometext": "new text",
"Id": 2,
"No": 12,
},
{
"info": "old text"
"sometext": "old text",
"info": "new text"
"sometext": "new text",
"Id": 68,
"No": 22,
},
{
"info": "old text"
"sometext": "old text",
"info": "new text"
"sometext": "new text",
"Id": 87,
"No": 15,
},
{
"info": "old text"
"sometext": "old text",
"info": "new text"
"sometext": "new text",
}

]

请注意 旧文本和新文本只是虚拟文本,而不是实际文本,与 NewTextGen() 虚拟方法相同,因为我只是想知道我是什么我的代码做错了

<小时/>

更新解决了我的问题,检查答案

最佳答案

您在每次迭代中编写整个“arrayObj”。可能的意图是写出“burObj”。

gson.toJson(burObj, new JsonWriter(bw));

关于java - 更新 json 数组文件中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56771909/

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