AsfK
AsfK

Reputation: 3476

gson create corrupted json file

In the bottom line I have to create a large json file (14K records, about 25 fields in each one). Meanwhile I starting the project with "small" data and I failed to format the json file, after quick invisigation I figure out the file is corrupted, "cut" in tine 964.

Than I did a quick test, using this code:

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);

And then end of the json file looks like this:

"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":"

As you can see the file is broken at "a8":".

What should I do to get a full json file? btw, filesize is 96kb, not think it's so big...

Upvotes: 0

Views: 425

Answers (1)

Uday Chauhan
Uday Chauhan

Reputation: 1148

This is working snippet.

        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();
        }
    }

You forget to close the filewriter and you need to put gson.toJson(hashList, writer); inside try catch block.

Upvotes: 2

Related Questions