简体   繁体   English

Gson 到 append json object 在 java 中的 json 文件中的数组中

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

I am trying to store a game result in a JSON file.我正在尝试将游戏结果存储在 JSON 文件中。 The results are stored when the game is over, and are supposed to be displayed afterwards in a table.结果在游戏结束时存储,并应在之后显示在表格中。

I have this function that creates the game score and adds it to json file using GSON我有这个 function 创建游戏分数并使用 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);
        }
}

That method creates a JSON file that looks like this:该方法创建一个 JSON 文件,如下所示:

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

The problem is when I try to add another game result to the file, it appears like this:问题是当我尝试将另一个游戏结果添加到文件时,它看起来像这样:

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

Which is not a valid JSON file and so it is not read properly when I try to show the results later.这不是有效的 JSON 文件,因此当我稍后尝试显示结果时无法正确读取。 How can I use Gson (or anything else really) to show the results in the JSON file like this:我如何使用 Gson(或其他任何东西)来显示 JSON 文件中的结果,如下所示:

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

Any suggestion will be helpful!任何建议都会有所帮助!

this should work for you, but if there are a lot of entries in the file, then I think it will be necessary to change the approach.这应该对你有用,但如果文件中有很多条目,那么我认为有必要改变方法。

add maven dependecy:添加 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
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM