JSON.simple Tutorial - Read and Write JSON in Java

JSON.simple is a simple Java library for JSON processing, read and write JSON data and full compliance with JSON specification (RFC4627).
In this JSON.simple tutorial, we will see quick examples to write JSON file with JSON.simple and then we will read JSON file back.
Check out read and write JSON in Java using JSON-P at https://www.javaguides.net/2019/07/read-and-write-json-in-java.html.

JSON.simple maven dependency

You can download the latest release of JSON.simple library at https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple
Here is the latest maven dependency:
<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
	<groupId>com.googlecode.json-simple</groupId>
	<artifactId>json-simple</artifactId>
	<version>1.1.1</version>
</dependency>
In the below examples, we use two important classes of JSON.simple library to read and write a JSON to file in Java.
  • JSONArray: To write data in JSON arrays. Use its add() method to add objects of type JSONObject.
  • JSONObject : To write JSON objects. Use it’s put() method to populate fields.

1. Write JSON to File in Java using JSON.simple Library

In this example, we create an array with 3 user objects using JSONObject and JSONArray classes and write to a file "users.json":
package net.javaguides.jsonsimple;

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

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

public class WriteJSON {

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {

        //First User
        JSONObject userDetails = new JSONObject();
        userDetails.put("id", 100);
        userDetails.put("firstName", "Ramesh");
        userDetails.put("lastName", "Fadatare");
        userDetails.put("userName", "Ramesh Fadatare");
        userDetails.put("email", "ramesh@gmail.com");


        //Second user
        JSONObject userDetails1 = new JSONObject();
        userDetails1.put("id", 101);
        userDetails1.put("firstName", "John");
        userDetails1.put("lastName", "Cena");
        userDetails1.put("userName", "John Cena");
        userDetails1.put("email", "john@gmail.com");

        // Third User
        JSONObject userDetails2 = new JSONObject();
        userDetails2.put("id", 102);
        userDetails2.put("firstName", "Tony");
        userDetails2.put("lastName", "stark");
        userDetails2.put("userName", "Tony stark");
        userDetails2.put("email", "tony@gmail.com");

        //Add employees to list
        JSONArray userList = new JSONArray();
        userList.add(userDetails);
        userList.add(userDetails1);
        userList.add(userDetails2);

        //Write JSON file
        try (FileWriter file = new FileWriter("users.json")) {

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

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
The above program writes a JSON to the file. Here is "users.json" file content:
[
	{
		"firstName": "Ramesh",
		"lastName": "Fadatare",
		"id": 100,
		"userName": "Ramesh Fadatare",
		"email": "ramesh@gmail.com"
	},
	{
		"firstName": "John",
		"lastName": "Cena",
		"id": 101,
		"userName": "John Cena",
		"email": "john@gmail.com"
	},
	{
		"firstName": "Tony",
		"lastName": "stark",
		"id": 102,
		"userName": "Tony stark",
		"email": "tony@gmail.com"
	}
]

2. Read JSON from a File in Java using JSON-simple Library

To read JSON from a file, we will be using the JSON file we created in the previous example.
package net.javaguides.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 ReadJSON {

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        // JSON parser object to parse read file
        JSONParser jsonParser = new JSONParser();

        try (FileReader reader = new FileReader("users.json")) {
            // Read JSON file
            Object obj = jsonParser.parse(reader);

            JSONArray userList = (JSONArray) obj;

            // Iterate over employee array
            userList.forEach(user - > parseUserObject((JSONObject) user));

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

    private static void parseUserObject(JSONObject user) {

        // Get user first name
        Long id = (Long) user.get("id");
        System.out.println(id);

        // Get user first name
        String firstName = (String) user.get("firstName");
        System.out.println(firstName);

        // Get user last name
        String lastName = (String) user.get("lastName");
        System.out.println(lastName);

        // Get user website name
        String userName = (String) user.get("userName");
        System.out.println(userName);

        // Get user email name
        String email = (String) user.get("email");
        System.out.println(email);
    }
}
Output:
100
Ramesh
Fadatare
Ramesh Fadatare
ramesh@gmail.com
101
John
Cena
John Cena
john@gmail.com
102
Tony
stark
Tony stark
tony@gmail.com

Reference

Comments