0

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.

6
  • Yep, that's how it works. You'd need to read the file first and append the data, then write it all. Otherwise you'd also create invalid json. Consider using a database instead of files. Commented Mar 29, 2019 at 9:24
  • Could you give me an example of append? I cannot use databases for this task Commented Mar 29, 2019 at 9:25
  • 3
    it seems its a duplicate of stackoverflow.com/questions/43981487/… Commented Mar 29, 2019 at 9:25
  • the first response doesn't work at all, the json that you get from it it's invalid and the second one I cannot try, it says that seqWriter its an invalid refference Commented Mar 29, 2019 at 9:37
  • Your code keeps writing a new file. What you need to do is addcode that tries to read the file and append to it and only create a file if it doesn't exist. Commented Mar 29, 2019 at 9:50

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

could you provide me an example code please? I really have no clue how to do so in json
This is the error message that I get from this code pastebin.com/fZ38YAcA
How does your file look like? Please add it to your quesion. The code above assumes a yet-created file with a list of objects or an empty list to start with.
at the moment my file it's empty
Then just add an empty array like []. I've elaborated a little bit more on the pre-conditions and generic deserialization in my answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.