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!
Advertisement
Answer
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:
<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 } }