How to create and write JSON with JSON.simple in Java

HOME

This article shows how to write a JSON using JSON.simple.

JSON.simple is available at the Central Maven Repository. Maven users add this to the POM.

<!-- https://mvnrepository.com/artifact/com.github.cliftonlabs/json-simple -->
<dependency>
    <groupId>com.github.cliftonlabs</groupId>
    <artifactId>json-simple</artifactId>
    <version>4.0.1</version>
</dependency>

If the project is Gradle, add the below dependency in build.gradle.

// https://mvnrepository.com/artifact/com.github.cliftonlabs/json-simple
implementation("com.github.cliftonlabs:json-simple:4.0.1")

Write Simple JSON to File using JSON.simple

{ 
    "Working Days":[ 
                             "Monday",
                             "Tuesday",
                             "Wednesday"
                             ],
    "Salary":4500.0,
    "Name":"Vibha"
}

import com.github.cliftonlabs.json_simple.JsonArray;
import com.github.cliftonlabs.json_simple.JsonObject;
import com.github.cliftonlabs.json_simple.Jsoner;

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

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

        // JSON String
        JsonObject jsonObject = new JsonObject();
        jsonObject.put("Name", "Vibha");
        jsonObject.put("Salary", 4500.00);

        // JSON Array
        JsonArray list = new JsonArray();
        list.add("Monday");
        list.add("Tuesday");
        list.add("Wednesday");

        jsonObject.put("Working Days", list);
        System.out.println(Jsoner.serialize(jsonObject));

        try (FileWriter fileWriter = new FileWriter("src/test/resources/Payloads/Employee.json")) {
            Jsoner.serialize(jsonObject, fileWriter);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

JsonObject jsonObject = new JsonObject();
jsonObject.put("Name", "Vibha");
jsonObject.put("Salary", 4500.00);
JsonArray list = new JsonArray();
list.add("Monday");
list.add("Tuesday");
list.add("Wednesday");
jsonObject.put("Working Days", list);
 try (FileWriter fileWriter = new FileWriter("src/test/resources/Payloads/Employee.json")) {
            Jsoner.serialize(jsonObject, fileWriter);

  } 

{
  "Working Days": ["Monday","Tuesday","Wednesday"],
  "Salary":{
    "Bonus":{
      "Quaterly":125.0,
      "Monthly":45.0,
      "Yearly":500.0
    },
    "Fixed":4000.0
  },"Name": {
  "Forename":"Vibha",
  "Surname":"Singh"
 }
}

import com.github.cliftonlabs.json_simple.JsonArray;
import com.github.cliftonlabs.json_simple.JsonObject;
import com.github.cliftonlabs.json_simple.Jsoner;

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

public class WriteComplexJson {

    public static void main(String[] args) {

        JsonObject jsonObject = new JsonObject();

        //Name
        JsonObject name = new JsonObject();
        name.put("Forename", "Vibha");
        name.put("Surname", "Singh");
        jsonObject.put("Name", name);

        //Salary
        JsonObject salary = new JsonObject();
        salary.put("Fixed", 4000.00);

        //Bonus
        JsonObject bonus = new JsonObject();
        bonus.put("Monthly", 45.00);
        bonus.put("Quaterly", 125.00);
        bonus.put("Yearly", 500.00);

        salary.put("Bonus",  bonus);
        jsonObject.put("Salary", salary);

        // JSON Array
        JsonArray list = new JsonArray();
        list.add("Monday");
        list.add("Tuesday");
        list.add("Wednesday");
        jsonObject.put("Working Days", list);

        System.out.println(Jsoner.serialize(jsonObject));

        try (FileWriter fileWriter = new FileWriter("src/test/resources/Payloads/EmployeeDetails.json")) {
            Jsoner.serialize(jsonObject, fileWriter);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

 JsonObject jsonObject = new JsonObject();
JsonObject name = new JsonObject();
name.put("Forename", "Vibha");
name.put("Surname", "Singh");
jsonObject.put("Name", name);
//Salary
JsonObject salary = new JsonObject();
salary.put("Fixed", 4000.00);
//Bonus
JsonObject bonus = new JsonObject();
bonus.put("Monthly", 45.00);
bonus.put("Quaterly", 125.00);
bonus.put("Yearly", 500.00);

salary.put("Bonus",  bonus);
jsonObject.put("Salary", salary);
// JSON Array
JsonArray list = new JsonArray();
list.add("Monday");
list.add("Tuesday");
list.add("Wednesday");

jsonObject.put("Working Days", list);
jsonObject.put("Working Days", list);
System.out.println(Jsoner.serialize(jsonObject));

7. Writing the JSON to a File

The `try-with-resources` statement is used to ensure the `FileWriter` is closed automatically. A `FileWriter` writes the serialized JSON object to a file at `src/test/resources/Payloads/EmployeeDetails.json`.

 try (FileWriter fileWriter = new FileWriter("src/test/resources/Payloads/Employee.json")) {
            Jsoner.serialize(jsonObject, fileWriter); }

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

How to Read JSON with JSON.simple

HOME

This article shows how to read JSON using JSON.simple.

JSON.simple is available at the Central Maven Repository. Maven users add this to the POM.

<!-- https://mvnrepository.com/artifact/com.github.cliftonlabs/json-simple -->
<dependency>
    <groupId>com.github.cliftonlabs</groupId>
    <artifactId>json-simple</artifactId>
    <version>4.0.1</version>
</dependency>

If the project is Gradle, add the below dependency in build.gradle.

// https://mvnrepository.com/artifact/com.github.cliftonlabs/json-simple
implementation("com.github.cliftonlabs:json-simple:4.0.1")

Read Simple JSON from File using JSON.simple

{
  "store": {
    "book": "Harry Potter",
    "author": "J K Rowling",
    "price": 100
  }
}

import com.github.cliftonlabs.json_simple.JsonException;
import com.github.cliftonlabs.json_simple.JsonObject;
import com.github.cliftonlabs.json_simple.Jsoner;

import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;

public class SimpleJsonExample {

    public static void main(String args[]) throws IOException {

        String jsonString = new String(Files.readAllBytes(Paths.get("src/test/resources/Payloads/simple.json")));
        try {
            JsonObject jsonObject = (JsonObject) Jsoner.deserialize(jsonString);

            // Accessing the "store" object
            JsonObject store = (JsonObject) jsonObject.get("store");

            // Accessing the "book" object
            String book = (String) store.get("book");
            System.out.println("Book: " + book);

            // Accessing the "author" object
            String author = (String) store.get("author");
            System.out.println("Author - " + author);

            // Accessing the "price" field
            BigDecimal price = (BigDecimal) store.get("price");
            System.out.println("Price: " + price);

        } catch (JsonException e) {
            throw new RuntimeException(e);
        }
    }
}

String jsonString = new String(Files.readAllBytes(Paths.get("src/test/resources/Payloads/simple.json")));
JsonObject jsonObject = (JsonObject) Jsoner.deserialize(jsonString);
 JsonObject store = (JsonObject) jsonObject.get("store");
String book = (String) store.get("book");
System.out.println("Book: " + book);
String author = (String) store.get("author");
System.out.println("Author - " + author);
BigDecimal price = (BigDecimal) store.get("price");
System.out.println("Price: " + price);

public class ComplexJsonExample {

    public static void main(String args[]) throws IOException {

        String jsonString = new String(Files.readAllBytes(Paths.get("src/test/resources/Payloads/complex.json")));
        try {
            JsonObject jsonObject = (JsonObject) Jsoner.deserialize(jsonString);

            // Accessing the "store" object
            JsonObject store = (JsonObject) jsonObject.get("store");

            // Accessing the "book" array
            JsonArray books = (JsonArray) store.get("book");
            for (Object bookObj : books) {
                JsonObject book = (JsonObject) bookObj;
                String category = (String) book.get("category");
                String author = (String) book.get("author");
                String title = (String) book.get("title");
                BigDecimal price = (BigDecimal) book.get("price");

                System.out.println("Book: " + title + " (Category: " + category + ", Author: " + author + ", Price: " + price + ")");
            }

            // Accessing the "bicycle" object
            JsonObject bicycle = (JsonObject) store.get("bicycle");
            String color = (String) bicycle.get("color");
            BigDecimal bicyclePrice = (BigDecimal) bicycle.get("price");
            System.out.println("Bicycle: Color - " + color + ", Price - " + bicyclePrice);

            // Accessing the "expensive" field
            BigDecimal expensiveValue = (BigDecimal) jsonObject.get("expensive");
            System.out.println("Expensive threshold: " + expensiveValue);

        } catch (JsonException e) {
            throw new RuntimeException(e);
        }
    }
}
String jsonString = new String(Files.readAllBytes(Paths.get("src/test/resources/Payloads/complex.json")));
JsonObject jsonObject = (JsonObject) Jsoner.deserialize(jsonString);
 // Accessing the "store" object
JsonObject store = (JsonObject) jsonObject.get("store");

// Accessing the "book" array
JsonArray books = (JsonArray) store.get("book");
 for (Object bookObj : books) {
       JsonObject book = (JsonObject) bookObj;
       String category = (String) book.get("category");
       String author = (String) book.get("author");
       String title = (String) book.get("title");
       BigDecimal price = (BigDecimal) book.get("price");

        System.out.println("Book: " + title + " (Category: " + category + ", Author: " + author + ", Price: " + price + ")");
      }
 // Accessing the "bicycle" object
 JsonObject bicycle = (JsonObject) store.get("bicycle");
String color = (String) bicycle.get("color");
BigDecimal bicyclePrice = (BigDecimal) bicycle.get("price");
System.out.println("Bicycle: Color - " + color + ", Price - " + bicyclePrice);
BigDecimal expensiveValue = (BigDecimal) jsonObject.get("expensive");
System.out.println("Expensive threshold: " + expensiveValue);

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!