How do I convert Java Object to JSON?

To convert Java objects or POJOs (Plain Old Java Objects) to JSON we can use one of JSONObject constructor that takes an object as its argument. In the following example we will convert Student POJO into JSON string. Student class must provide the getter methods, JSONObject creates JSON string by calling these methods.

In this code snippet we do as follows:

  • Creates Student object and set its properties using the setter methods.
  • Create JSONObject called object and use the Student object as argument to its constructor.
  • JSONObject use getter methods to produces JSON string.
  • Call object.toString() method to get the JSON string.
package org.kodejava.json;

import org.json.JSONObject;
import org.kodejava.json.support.Student;

import java.util.Arrays;

public class PojoToJSON {
    public static void main(String[] args) {
        Student student = new Student();
        student.setId(1L);
        student.setName("Alice");
        student.setAge(20);
        student.setCourses(Arrays.asList("Engineering", "Finance", "Chemistry"));

        JSONObject object = new JSONObject(student);
        String json = object.toString();
        System.out.println(json);
    }
}

Running this code produces the following result:

{"courses":["Engineering","Finance","Chemistry"],"name":"Alice","id":1,"age":20}

The Student class use in the code above:

package org.kodejava.json.support;

import java.util.List;

public class Student {
    private Long id;
    private String name;
    private int age;
    private List<String> courses;

    // Getters and Setters removed for simplicity
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20240303</version>
    </dependency>
</dependencies>

Maven Central

How do I create JSON from a Map?

In the previous example we use JSONObject to directly put key-value pairs to create JSON string, using the various put() methods. Instead of doing that, we can also create JSON from a Map object. We create a Map with some key-value pairs in it, and pass it as an argument when instantiating a JSONObject.

These are the steps for creating JSON from a Map:

  • Create a Map object using a HashMap class.
  • Put some key-value pairs into the map object.
  • Create a JSONObject and pass the map as argument to its constructor.
  • Print the JSONObject, we call object.toString() to get the JSON string.

Let’s try the following code snippet.

package org.kodejava.json;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class JSONFromMap {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("id", "1");
        map.put("name", "Alice");
        map.put("age", "20");

        JSONObject object = new JSONObject(map);
        System.out.println(object);
    }
}

Running this code produces the following output:

{"name":"Alice","age":"20","id":"1"}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20240303</version>
    </dependency>
</dependencies>

Maven Central

How do I write JSON string using JSON-Java (org.json) library?

The following code snippet show you how to create JSON string using JSON-Java library. Create an instance of JSONObject and use the put() method to create a key-value pair for the JSON string. The JSONArray object can be used to create an array of list of values to the JSON string, we also use the put() method to add value to the list.

The JSONObject.toString() method accept parameter called indentFactor, this set the indentation level of the generated string, which also make the JSON string generated easier to read and look prettier.

package org.kodejava.json;

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

public class WriteJSONString {
    public static void main(String[] args) {
        JSONObject object = new JSONObject();
        object.put("id", 1L);
        object.put("name", "Alice");
        object.put("age", 20);

        JSONArray courses = new JSONArray();
        courses.put("Engineering");
        courses.put("Finance");
        courses.put("Chemistry");

        object.put("courses", courses);

        String jsonString = object.toString(2);
        System.out.println(jsonString);
    }
}

The result of the code snippet above is:

{
  "courses": [
    "Engineering",
    "Finance",
    "Chemistry"
  ],
  "name": "Alice",
  "id": 1,
  "age": 20
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20240303</version>
    </dependency>
</dependencies>

Maven Central

How do I read JSON file using JSON-Java (org.json) library?

In this example we are going to use the JSON-Java (org.json) library to read or parse JSON file. First we start by getting the InputStream of the JSON file to be read using getResourceAsStream() method. Next we construct a JSONTokener from the input stream and create an instance of JSONObject to read the JSON entries.

We can use method like getString(), getInt(), getLong(), etc. to read a key-value from the JSON file. The getJSONArray() method allow us to read a list of values returned in JSONArray object, which can be iterated to get each values represented by the key. Let’s see the detail code snippet below.

package org.kodejava.json;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.InputStream;

public class ReadJSONString {
    public static void main(String[] args) {
        // info.json
        // {
        //   "id": "1",
        //   "name": "Alice",
        //   "age": "20",
        //   "courses": [
        //     "Engineering",
        //     "Finance",
        //     "Chemistry"
        //   ]
        // }
        String resourceName = "/info.json";
        InputStream is = ReadJSONString.class.getResourceAsStream(resourceName);
        if (is == null) {
            throw new NullPointerException("Cannot find resource file " + resourceName);
        }

        JSONTokener tokener = new JSONTokener(is);
        JSONObject object = new JSONObject(tokener);
        System.out.println("Id  : " + object.getLong("id"));
        System.out.println("Name: " + object.getString("name"));
        System.out.println("Age : " + object.getInt("age"));

        System.out.println("Courses: ");
        JSONArray courses = object.getJSONArray("courses");
        for (int i = 0; i < courses.length(); i++) {
            System.out.println("  - " + courses.get(i));
        }
    }
}

The result of the code snippet above is:

Id  : 1
Name: Alice
Age : 20
Courses: 
  - Engineering
  - Finance
  - Chemistry

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20240303</version>
    </dependency>
</dependencies>

Maven Central