gson 创建损坏的 json 文件

gson create corrupted json file

最后,我必须创建一个大型 json 文件(14K 条记录,每条约 25 个字段)。 同时,我使用 "small" 数据启动项目,但未能格式化 json 文件,经过快速检查后我发现文件已损坏,"cut" in 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 块内。