I am trying to store a game result in a JSON file. 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
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:
{
"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. How can I use Gson (or anything else really) to show the results in the JSON file like this:
[
{
"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!