How to write JSON object to File in Java


In this Java tutorial, we are going to write JSON objects and JSON Array in a file using Java. To create the JSON file using Java program we need to add the JSON.simple jar in the project build path.

Download the JSON.simple or add the maven/gradle dependency in your project.

pom.xml
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

Check this: How to parse JSON in Java

build.gradle
compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'

Now create the object of JSONObject class of package org.json.simple.JSONObject and use the put(K,V) method to add the values where K = ObjectName and V = ObjectValue

JSONObject jsonObject = new JSONObject();
jsonObject.put("website", "www.websparrow.org");

Similarly, create the object of JSONArray class of package org.json.simple.JSONArray

JSONArray jsonArray = new JSONArray();
jsonArray.add("Java");
jsonObject.put("technology", jsonArray);

Finally, use the FileWriter class to write the JSONObject into a file.

Check the full example

JsonWriteExample.java
package org.websparrow;

import java.io.FileWriter;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class JsonWriteExample {
	public static void main(String[] args) {

		JSONObject jsonObject = new JSONObject();
		
		//JSON object and values
		jsonObject.put("name", "Atul Rai");
		jsonObject.put("occupation", "Blogger");
		jsonObject.put("location", "India");
		jsonObject.put("website", "www.websparrow.org");
		
		//JSON array and values
		JSONArray jsonArray = new JSONArray();
		jsonArray.add("Java");
		jsonArray.add("Struts");
		jsonArray.add("jQuery");
		jsonArray.add("JavaScript");
		jsonArray.add("Database");

		jsonObject.put("technology", jsonArray);

		// writing the JSONObject into a file(info.json)
		try {
			FileWriter fileWriter = new FileWriter("info.json");
			fileWriter.write(jsonObject.toJSONString());
			fileWriter.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(jsonObject);
	}

}

Output:

To check the object is crated in file or not, go to file location and open the file(info.json).

{
	"website":"www.websparrow.org",
	"occupation":"Blogger",
	"name":"Atul Rai",
	"location":"India",
	"technology":["Java","Struts","jQuery","JavaScript","Database"]
}

References

  1. Introducing JSON

Similar Posts

About the Author

Websparrow
I like sharing my experiments and ideas with everyone by writing articles on the latest technological trends.