gpt4 book ai didi

java - gson 创建损坏的 json 文件

转载 作者:行者123 更新时间:2023-12-02 08:42:11 25 4
gpt4 key购买 nike

在最后一行,我必须创建一个大的 json 文件(14K 记录,每个记录大约 25 个字段)。同时,我用“小”数据启动项目,但未能格式化 json 文件,经过快速检查后,我发现文件已损坏,在 tine 964 中“剪切”。

我使用以下代码进行了快速测试:

List<HashMap<String, String>> hashList = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
HashMap<String, String> map = new HashMap<>();
for (int j = 0; j < 10; j++) {
map.put("a" + j, "a" + j);
}
hashList.add(map);
}

Gson gson = new Gson();
FileWriter writer = null;
try {
writer = new FileWriter("C:\\testDir\\gsonTest.json");
} catch (IOException e) {
e.printStackTrace();
}
gson.toJson(hashList, writer);

然后 json 文件的末尾如下所示:

“a1”:“a1”,“a2”:“a2”,“a3”:“a3”,“a4”:“a4”,“a5”:“a5”,“a6”: “a6”,“a7”:“a7”,“a8”:“a8”,“a9”:“a9”,“a0”:“a0”},{“a1”:“a1”,“a2”: “a2”,“a3”:“a3”,“a4”:“a4”,“a5”:“a5”,“a6”:“a6”,“a7”:“a7”,“a8”:“a8” ","a9":"a9","a0":"a0"},{"a1":"a1","a2":"a2","a3":"a3","a4":"a4 ","a5":"a5","a6":"a6","a7":"a7","a8":"

如您所见,文件在 "a8":" 处损坏。

我应该怎么做才能获得完整的 json 文件?顺便说一句,文件大小是 96kb,没想到这么大......

最佳答案

这是工作片段。

        List<HashMap<String, String>> hashList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
HashMap<String, String> map = new HashMap<>();
for (int j = 0; j < 100; j++) {
map.put("a" + j, "a" + j);
}
hashList.add(map);
}

Gson gson = new Gson();
FileWriter writer = null;
try {
writer = new FileWriter("C:\\testDir\\gsonTest.json");
gson.toJson(hashList, writer);

} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
} else {
System.out.println("Buffer has not been initialized!");
}
} catch (IOException e) {
e.printStackTrace();
}
}

你忘记关闭文件编写器,你需要把 gson.toJson(hashList, writer);在 try catch block 内。

关于java - gson 创建损坏的 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61309215/

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