JSON.simple – Read and Write JSON

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

JSON.simple library is pretty old and has not been updated since march, 2012. Google GSON library is a 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.

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.

<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 the 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

Download Sourcecode

Comments are closed for this article!

Comments

6 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

Comments are closed for this article!

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode