如何在java中将数组列表中的多个自定义对象存储到json文件中?

时间:2022-07-21 21:17:11

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.

下面是编写JSON文件的Java代码。我对使用JSON非常陌生。我有一个名为myAnimals的arraylist,它有多个动物的对象(sloth、cat等),我想运行一个循环,这个循环遍历这些对象,并将JSON文件填充到存储它们的对象中。第一个。put只是一个例子,它是如何运行的,而不是0,理想情况下我应该有一个像I这样的引用变量循环遍历,这样我就可以添加所有的。这个想法是每次将一个新对象添加到arraylist中以保持jsonfile的更新。如果有人能给我一些建议,那就太好了。循环当前的问题是文件每次都会被覆盖,并且只有一个json对象而不是很多。

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();
        }

    }

1 个解决方案

#1


0  

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.

但是,您需要考虑用户从列表中删除动物的情况。在这种情况下,循环整个动物数组并覆盖你的动物。当时的json文件。

#1


0  

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.

但是,您需要考虑用户从列表中删除动物的情况。在这种情况下,循环整个动物数组并覆盖你的动物。当时的json文件。