How to write JSON to File in Java

0
24
Spread the love

How to write JSON to File in Java:


Hello everybody, In this 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.

So do not forget to add the maven/gradle dependency in your project.

pom.xml -> in maven

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>{verion*}</version>
</dependency>

in Gradle ->

compile group: 'com.googlecode.json-simple', name: 'json-simple', version: 'verion*'

 

Then create your Class in java

JsonWriteTest.java

package com.test.yourtechpage;

import java.io.FileWriter;

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

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

		JSONObject jsonObject = new JSONObject();
		
		//JSON object and values
		jsonObject.put("name", "Jhon Pit");
		jsonObject.put("occupation", "programmer");
		jsonObject.put("location", "USA");
		jsonObject.put("website", "https://yourtechpage.com");
		
		//JSON array and values
		JSONArray jsonArray = new JSONArray();
		jsonArray.add("Java");
		jsonArray.add("PHP");
		jsonArray.add("jQuery");
		jsonArray.add("JavaScript");
		jsonArray.add("SQL");     
                jsonArray.add("Android");
		jsonObject.put("technology", jsonArray);

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

}

 

finally run your program and see output below.

{
	"website":"www.yourtechpage.com",
	"occupation":"programmer",
	"name":"Jhon Pit", "location":"USA", "technology":["Java","PHP","jQuery","JavaScript","SQL","Android"] }

 

 

 

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here