Gson 在 java 中的 json 文件中的数组中追加 json 对象

Gson to append json object within an array in a json file in java

我正在尝试将游戏结果存储在 JSON 文件中。结果在游戏结束时存储,并应在之后显示在 table.

我有创建游戏分数并使用 GSON

将其添加到 json 文件的功能
 private void createGameScoreGson () throws Exception {
        var gson = new GsonBuilder().setPrettyPrinting().create();
        var score = new ScoreResult();
        score.setPlayerName(name);
        score.setSteps(steps);
        score.setTime(time);
        score.setSolved(solved);

        // writing to a json file
        File file = new File("src\main\resources\results.json");
        try (var writer = new FileWriter("resources\results.json", true)) {
            gson.toJson(score, writer);
        }
}

该方法创建一个 JSON 文件,如下所示:

{
    "playerName": "a",
    "steps": 1,
    "time": "00:00:11",
    "solved": false
}

问题是当我尝试将另一个游戏结果添加到文件时,它显示如下:

{
    "playerName": "a",
    "steps": 1,
    "time": "00:00:11",
    "solved": false
}
{
    "playerName": "b",
    "steps": 2,
    "time": "00:00:20",
    "solved": false
}

这不是有效的 JSON 文件,因此当我稍后尝试显示结果时无法正确读取它。 我如何使用 Gson(或其他任何东西)像这样在 JSON 文件中显示结果:

[
 {
    "playerName": "a",
    "steps": 1,
    "time": "00:00:11",
    "solved": false
 },
 {
    "playerName": "b",
    "steps": 2,
    "time": "00:00:20",
    "solved": false
 }
]

任何建议都会有所帮助!

这应该适合你,但如果文件中有很多条目,那么我认为有必要改变方法。

添加maven依赖:

        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>
public void createGameScoreGson () throws Exception {
        ScoreResult score = new ScoreResult();
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        JSONArray jsonArray = parseFromFile();
        
        // You can create file if you need
        try (FileWriter writer = new FileWriter("src/main/resources/results.json", false)) {
            String gs = gson.toJson(score);
            Map map = gson.fromJson(gson.toJson(score), Map.class);
            jsonArray.add(map);
            String jsonPretty = gson.toJson(jsonArray);
            writer.write(jsonPretty);
        }
    }
public JSONArray parseFromFile() throws IOException {
        JSONParser parser = new JSONParser();
        try {
            return (JSONArray) parser.parse(new FileReader("src/main/resources/results.json"));
        }
        catch (ParseException e){
            return new JSONArray();
        }
        catch (FileNotFoundException e){
            return null; // any code
        }
    }