Search code examples
javajsonobjectarraylistfilewriter

How to store multiple custom objects from an array list into json file in java?


obBelow is my Java code to write to JSON file. I'm quite new to using JSON. I have an arraylist called myAnimals and it has multiple objects of animals(sloth, cat etc.) I want to run a loop that goes through these objects and fills in the JSON file with objects storing them. The first .put is just an example of how it will go, instead of 0 I'd ideally have a reference variable like i that will loop through so I can add all. The idea is this runs every time a new object is added to the arraylist to keep the jsonfile updated. If anyone can advise me on how to do this, that would be great. The current issue with a loop is that the file would be overwritten each time and only have one json object not many.

public void writeJson(){
    JSONObject obj = new JSONObject();
    obj.put("name", myAnimals.get(0).getAnimalName());
    obj.put("penType", ?);
    obj.put("landSpace", ?);
    obj.put("waterSpace", ?);
    obj.put("airSpace", ?);

    try (FileWriter file = new FileWriter("animals.json")) {

        file.write(obj.toJSONString());
        file.flush();

    } catch (IOException e) {
        e.printStackTrace();
    }

}

Solution

  • change

    try (FileWriter file = new FileWriter("animals.json")) {
    

    to

    try (FileWriter file = new FileWriter("animals.json", true)) {
    

    adding the true boolean value will append to the end of your file instead of overwriting it. This will work for adding new ones to your file to keep it up to date.

    However you need to consider the case where a user erases an animal from your list. In that case, loop the entire arraylist of animals and overwrite whatever is in your animals.json file at that time.