Terchila Marian
Terchila Marian

Reputation: 2520

How to store java objects in json file?

I intend to store multiple java objects into a JSON file but I got no clue how to do so. That's my code :

private static final String JSONFILEPATH = "config.json";

public void addSavefile(Savefile sf){
    ObjectMapper mapper = new ObjectMapper();
    try{
        mapper.writeValue(new File(JSONFILEPATH), sf);
    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

But it works just once, after I try to add more objects it just deletes the last one stored and replaces it with the new one.

Upvotes: 0

Views: 1918

Answers (1)

mle
mle

Reputation: 2542

I suggest, that you never write a single Savefile object in your file but already start with a List<Savefile>. Then it is much easier to append further objects to this list with the following steps:

  1. Read your yet-created file
  2. Deserialize the contents to a List<Savefile>
  3. Write the now augmented list back to the file (deleting all the content which yet exists in this file)

Put into code (simplified with a Test object instead of your Savefile) this would look like:

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        File file = new File("/home/user/test.json");

        // step 1 – assuming you already habe or wrote a file with empty JSON list []
        List<Test> tests = mapper.readValue(file, new TypeReference<List<Test>>(){});

        // step 2
        tests.add(new Test(4));

        // step 3
        mapper.writeValue(file, tests);
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Test {
        int a;
    }

Annotations come from Lombok.

The trick with new TypeReference<List<Test>>(){} helps you to deserialize objects with generics. Keep in mind that before starting you either have to have a file with an empty JSON array or you skip the first step at all.

Upvotes: 2

Related Questions