Skip to content
Advertisement

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. 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

JavaScript

That method creates a JSON file that looks like this:

JavaScript

The problem is when I try to add another game result to the file, it appears like this:

JavaScript

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:

JavaScript

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:

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement