HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Java Libraries / Java read json and write json example – JSON.simple

Java read json and write json example – JSON.simple

JSON.simple is lightweight JSON processing library which can be used to read JSON, write JSON file. Produced JSON will be in full compliance with JSON specification (RFC4627).

In this JSON tutorial, we will see quick examples to write JSON file with JSON.simple and then we will read JSON file back.

Table of Contents

1. Json.simple maven dependency
2. Write JSON to file with json-simple
3. Read JSON from file with json-simple
4. Download Sourcecode

1. Json.simple maven dependency

Update pom.xml with json-simple maven dependency. [Link]

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

2. Write JSON to file in Java with json-simple

To write JSON to file, we will be working to mainly two objects:

  1. JSONArray : To write data in json arrays. Use its add() method to add objects of type JSONObject.
  2. JSONObject : To write json objects. Use it’s put() method to populate fields.

After populating above objects, use FileWriter instance to write JSON file.

package com.howtodoinjava.demo.jsonsimple;

import java.io.FileWriter;
import java.io.IOException;

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

public class WriteJSONExample
{
    @SuppressWarnings("unchecked")
	public static void main( String[] args )
    {
    	//First Employee
    	JSONObject employeeDetails = new JSONObject();
    	employeeDetails.put("firstName", "Lokesh");
    	employeeDetails.put("lastName", "Gupta");
    	employeeDetails.put("website", "howtodoinjava.com");
    	
    	JSONObject employeeObject = new JSONObject(); 
    	employeeObject.put("employee", employeeDetails);
    	
    	//Second Employee
    	JSONObject employeeDetails2 = new JSONObject();
    	employeeDetails2.put("firstName", "Brian");
    	employeeDetails2.put("lastName", "Schultz");
    	employeeDetails2.put("website", "example.com");
    	
    	JSONObject employeeObject2 = new JSONObject(); 
    	employeeObject2.put("employee", employeeDetails2);
    	
    	//Add employees to list
    	JSONArray employeeList = new JSONArray();
    	employeeList.add(employeeObject);
    	employeeList.add(employeeObject2);
    	
    	//Write JSON file
    	try (FileWriter file = new FileWriter("employees.json")) {

            file.write(employeeList.toJSONString());
            file.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Program Output.

[
	{
		"employee": {
			"firstName": "Lokesh",
			"lastName": "Gupta",
			"website": "howtodoinjava.com"
		}
	},
	{
		"employee": {
			"firstName": "Brian",
			"lastName": "Schultz",
			"website": "example.com"
		}
	}
]

3. Read JSON from file in Java with json-simple

To read JSON from file, we will be using the JSON file we created in the previous example.

  1. First of all, we will create JSONParser instance to parse JSON file.
  2. Use FileReader to read JSON file and pass it to parser.
  3. Start reading the JSON objects one by one, based on their type i.e. JSONArray and JSONObject.
package com.howtodoinjava.demo.jsonsimple;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class ReadJSONExample 
{
	@SuppressWarnings("unchecked")
	public static void main(String[] args) 
	{
		//JSON parser object to parse read file
		JSONParser jsonParser = new JSONParser();
		
		try (FileReader reader = new FileReader("employees.json"))
		{
			//Read JSON file
            Object obj = jsonParser.parse(reader);

            JSONArray employeeList = (JSONArray) obj;
            System.out.println(employeeList);
            
            //Iterate over employee array
            employeeList.forEach( emp -> parseEmployeeObject( (JSONObject) emp ) );

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
	}

	private static void parseEmployeeObject(JSONObject employee) 
	{
		//Get employee object within list
		JSONObject employeeObject = (JSONObject) employee.get("employee");
		
		//Get employee first name
		String firstName = (String) employeeObject.get("firstName");	
		System.out.println(firstName);
		
		//Get employee last name
		String lastName = (String) employeeObject.get("lastName");	
		System.out.println(lastName);
		
		//Get employee website name
		String website = (String) employeeObject.get("website");	
		System.out.println(website);
	}
}

Program Output.

[{"employee":{"firstName":"Lokesh","lastName":"Gupta","website":"howtodoinjava.com"}},{"employee":{"firstName":"Brian","lastName":"Schultz","website":"example.com"}}]

Lokesh
Gupta
howtodoinjava.com

Brian
Schultz
example.com

4. Download Sourcecode

Download Sourcecode

Happy Learning !!

Reference:

JSON.simple on Git
JSON.simple Google Code Archive

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Sonal Gupta

    August 11, 2020

    I have followed exactly as you have mentioned in the article . but was getting errors. following is the code snippet

    
    public class WriteJsonExample {
    
    	@SuppressWarnings("unchecked")
    	public static void main(String[] args) {
    		//first employee
    		JSONObject employeeDetails= new JSONObject();
    		employeeDetails.put("firstName", "Sonal");
    		employeeDetails.put("lastName", "Gupta");
    		employeeDetails.put("company","TCS");
    		
    		JSONObject employeeObject= new JSONObject();
    		employeeObject.put("employee", employeeObject);
    		
    		//second employee
    		JSONObject employeeDetails2 = new JSONObject();
    		employeeDetails2.put("firstName", "Harsh");
    		employeeDetails2.put("lastName", "Vardhhan");
    		employeeDetails2.put("company", "Infosys");
    		
    		JSONObject employeeObject2= new JSONObject();
    		employeeObject2.put("employee", employeeObject2);
    		
    		//Add employees to list
    		JSONArray employeeList= new JSONArray();
    		employeeList.add(employeeObject);
    		employeeList.add(employeeObject2);
    		
    		//WriteJsonFile
    		try(FileWriter file = new FileWriter("employees.json")){
    			file.write(employeeList.toJSONString());
    			file.flush();
    			
    		}catch(IOException e){
    			e.printStackTrace();
    		}
    
    	}
    
    }
    
    

    following are the error logs

    Exception in thread “main” java.lang.StackOverflowError
    at java.base/java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:748)
    at java.base/java.lang.StringBuffer.append(StringBuffer.java:424)
    at org.json.simple.JSONValue.escape(JSONValue.java:266)
    at org.json.simple.JSONObject.toJSONString(JSONObject.java:116)
    at org.json.simple.JSONObject.toJSONString(JSONObject.java:101)
    at org.json.simple.JSONObject.toJSONString(JSONObject.java:108)
    …..
    and similar long list of errors

  2. Peter

    November 21, 2019

    Had to make some changes for it to compile, namely:

                Object obj = jsonParser.parse(reader);
                JSONArray userList = new JSONArray();
                userList.add(obj);
    

    instead of directly casting like shown in the example here

                Object obj = jsonParser.parse(reader);
                JSONArray employeeList = (JSONArray) obj;
    
  3. Louise

    August 5, 2019

    Hi,

    I followed the example above but the JSON wrote to file does not have indentations. Am I doing something wrong?

    Thank you so much!

  4. SRav

    July 23, 2019

    Hello,
    How can I update just one entity value in json file?
    For example,
    I have a json file with all the data in it and
    I have to a change “firstname”: “lokesh”
    to some other value which is stored in a string.
    How can I just write this value into my json file using java
    Please help.
    Thanks

  5. Sam

    March 28, 2019

    Hi, how do I do this with a 500GB json file (wikidata)?

  6. Daniel Israel

    March 10, 2019

    How can you parse a FileReader object? What is a FileReader object?
    In comparison, I want to get a JSON file read in, then make it to string, then I know how to deal with it, but my parse method won’t take a FileReader.

Comments are closed on this article!

Search Tutorials

Open Source Libraries

  • Apache POI Tutorial
  • Apache HttpClient Tutorial
  • iText Tutorial
  • Super CSV Tutorial
  • OpenCSV Tutorial
  • Google Gson Tutorial
  • JMeter Tutorial
  • Docker Tutorial
  • JSON.simple Tutorial
  • RxJava Tutorial
  • Jsoup Parser Tutorial
  • PowerMock Tutorial

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces