JSON.simple – Read and Write JSON String

JSON.simple is lightweight JSON processing library which can be used to read and write JSON files and strings. The encoded/decoded JSON will be in full compliance with JSON specification (RFC4627).

Note: This library is pretty old now. Google GSON library is also another good option for reading and writing JSON.

In this Java JSON tutorial, we will first see a quick example of writing to a JSON file and then we will read JSON from the file.

Table of Contents

1. Json.simple Features
2. Maven Dependencies
3. Write JSON to file with json-simple
4. Read JSON from file with json-simple

1. Json.simple Features

  • Full compliance with JSON specification (RFC4627).
  • Supports encode, decode/parse and escape JSON.
  • Easy to use by reusing Map and List interfaces.
  • Supports streaming output of JSON text.
  • High performance.
  • No dependency on external libraries.

2. Json.simple Maven

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>

3. Write JSON to the File

To write JSON test into the file, we will be working with mainly two classes:

  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 the 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")) {
            //We can write any JSONArray or JSONObject instance to the file
            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"
		}
	}
]

4. Read JSON from a File

To read JSON from file, we will use 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

Happy Learning !!

Reference:

JSON.simple on Git
JSON.simple Google Code Archive

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

6 thoughts on “JSON.simple – Read and Write JSON String”

  1. 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

    Reply
  2. 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;
    
    Reply
  3. 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!

    Reply
  4. 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

    Reply
  5. 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.

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.