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.
Amazing article. Good for people like me who is learning concepts of java.
Keep learning Juan.
Hey,
Can we convert Java HashMap class in Json…..like Map …
Thanks man!
Yes Roberto, you can do it. Drop us a message if you are not able to do it. Our expert team will help you with Java coding.
WOW!! This is exactly what I was looking for. After hours of searching, I found it here. Thanks for sharing the code to convert Java ArrayList to JSON format and saving it to a .json file
We are happy that you found this Java object conversion to JSON tutorial awesome. Keep learning !!
Simple and easy tutorial.. Keep the good work going 🙂
I like the way writer has written the article. Keep up the good work.