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

How to pretty print JSON string using Jackson?

The following example demonstrates how to pretty print the JSON string produces by Jackson library. To produce well formatted JSON string we create the ObjectMapper instance and enable the SerializationFeature.INDENT_OUTPUT feature. To enable this feature we need to call the enable() method of the ObjectMapper and provide the feature to be enabled.

ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
String json = mapper.writeValueAsString(recording);
System.out.println(json);

On the second example below we format unformatted JSON string. To do this we use the ObjectMapper‘s readValue(String, Class<T>) method which accept the JSON string and Object.class as the value type. The readValue() method return an Object. To format the JSON object we call mapper.writerWithDefaultPrettyPrinter().writeValueAsString(Object). This will produce a pretty formatted JSON.

ObjectMapper mapper = new ObjectMapper();
Object jsonObject = mapper.readValue(json, Object.class);
String prettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
System.out.println(prettyJson);

Below is the complete code snippets.

package org.kodejava.jackson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.kodejava.jackson.support.Artist;
import org.kodejava.jackson.support.Label;
import org.kodejava.jackson.support.Recording;

import java.io.IOException;
import java.time.LocalDate;
import java.time.Month;

public class JsonIndentOutput {
    public static void main(String[] args) {
        JsonIndentOutput.formatObjectToJsonString();
        JsonIndentOutput.formatJsonString();
    }

    private static void formatObjectToJsonString() {
        Recording recording = new Recording();
        recording.setId(1L);
        recording.setTitle("Yellow Submarine");
        recording.setReleaseDate(LocalDate.of(1969, Month.JANUARY, 17));
        recording.setArtist(new Artist(1L, "The Beatles"));
        recording.setLabel(new Label(1L, "Apple"));

        ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
        try {
            String json = mapper.writeValueAsString(recording);
            System.out.println(json);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    private static void formatJsonString() {
        String json = """
                {"id":1,"title":"Yellow Submarine","releaseDate":"1969-01-17","artist":{"id":1,"name":"The Beatles"},"label":{"id":1,"name":"Apple"}}
                """;
        ObjectMapper mapper = new ObjectMapper();
        try {
            Object jsonObject = mapper.readValue(json, Object.class);
            String prettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
            System.out.println(prettyJson);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The code snippet above will pretty print the following JSON string:

{
  "id" : 1,
  "title" : "Yellow Submarine",
  "releaseDate" : "1969-01-17",
  "artist" : {
    "id" : 1,
    "name" : "The Beatles"
  },
  "label" : {
    "id" : 1,
    "name" : "Apple"
  }
}

Here are the structure of Recording, Artist and Label classes.

package org.kodejava.jackson.support;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.kodejava.jackson.LocalDateDeserializer;
import org.kodejava.jackson.LocalDateSerializer;

import java.time.LocalDate;

public class Recording {
    private Long id;
    private String title;

    @JsonDeserialize(using = LocalDateDeserializer.class)
    @JsonSerialize(using = LocalDateSerializer.class)
    private LocalDate releaseDate;
    private Artist artist;
    private Label label;

    // Getters and Setters
}
package org.kodejava.jackson.support;

public class Artist {
    private Long id;
    private String name;

    public Artist() {
    }

    public Artist(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    // Getters and Setters
}
package org.kodejava.jackson.support;

public class Label {
    private Long id;
    private String title;

    public Label(Long id, String title) {
        this.id = id;
        this.title = title;
    }

    // Getters and Setters
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.17.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.17.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.17.1</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central