Looking how to write an ArrayList object data to JSON file in Java? Here is a simple and easy way to do it.


// The Tab format
private static final int TAB = 4;

// Path of file
private static String filePath = "./data/data.json";

public void saveToJson(ArrayList<Task> tasks) {
      
        JSONArray jarray = new JSONArray(tasks.toArray());
        try {
            FileWriter writer = new FileWriter(new File(filePath));
            writer.write(jarray.toString(TAB));
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

The above function takes in an ArrayList object name tasks.

On line number 8 we create a JSONArray object name jarray and pass the tasks.toArray().

Note: toArray() function returns a list of the array containing all elements in the list.

We also convert JSON object to String using the toString() method.

The output data is written in the data.json file and will look something like this depending on your ArrayList object and the data it contains.


[
    {
        "subTasks": [],
        "ID": 1,
        "completed": true,
        "title": "study",
        "content": "cpsc"
    },
    {
        "subTasks": [],
        "ID": 2,
        "completed": false,
        "title": "sports",
        "content": "cricket"
    },
    {
        "subTasks": [],
        "ID": 3,
        "completed": false,
        "title": "movie",
        "content": "Avengers"
    }
]

You can use the above function directly just make sure you change the ArrayList<type> in the function parameter and the file path where you need the data.json file.

Hope you liked this article on ArrayList to JSON object conversion and File Writing.

More Java tutorial-

Follow us on Facebook and Instagram. You can also subscribe to our newsletter.