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>20230618</version>
        <type>bundle</type>
    </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>20230618</version>
        <type>bundle</type>
    </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.15.2</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.15.2</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.15.2</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How to format LocalDate object using Jackson?

We have a Recording class which has a Java 8 java.time.LocalDate property. We need to deserialize and serialize this property from and to JSON string. To do this we can use the @JsonDeserialize and @JsonSerialize annotations to annotate the LocalDate property of the Recording class.

@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate releaseDate;

To use the annotation we need to create a class to deserialize and serialize the value. To create a deserializer class we create a class that extends StdDeserializer. The serializer class extends the StdSerializer class. Below is the definition of the LocalDateSerializer and LocalDateDeserializer class.

package org.kodejava.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class LocalDateSerializer extends StdSerializer<LocalDate> {

    public LocalDateSerializer() {
        super(LocalDate.class);
    }

    @Override
    public void serialize(LocalDate value, JsonGenerator generator, SerializerProvider provider) throws IOException {
        generator.writeString(value.format(DateTimeFormatter.ISO_LOCAL_DATE));
    }
}
package org.kodejava.jackson;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;

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

public class LocalDateDeserializer extends StdDeserializer<LocalDate> {

    protected LocalDateDeserializer() {
        super(LocalDate.class);
    }

    @Override
    public LocalDate deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        return LocalDate.parse(parser.readValueAs(String.class));
    }
}

Let’s create a simple class that convert Recording object into JSON string and apply the date formatter defined in the LocalDateSerializer class.

package org.kodejava.jackson;

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

import java.time.LocalDate;
import java.time.Month;

public class RecordingToJson {
    public static void main(String[] args) {
        Recording recording = new Recording();
        recording.setId(1L);
        recording.setTitle("Twist and Shout");
        recording.setReleaseDate(LocalDate.of(1964, Month.FEBRUARY, 3));

        ObjectMapper mapper = new ObjectMapper();
        try {
            String json = mapper.writeValueAsString(recording);
            System.out.println("JSON = " + json);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}

The output of the code snippet above is:

JSON = {"id":1,"title":"Twist and Shout","releaseDate":"1964-02-03"}

And here is the complete definition of the Recording class.

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;

    // Getters and Setters

    @Override
    public String toString() {
        return "Recording{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", releaseDate=" + releaseDate +
                '}';
    }
}

Maven Dependencies

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

Maven Central Maven Central Maven Central

How to read and write Java object to JSON file?

The following example demonstrate how to serialize and deserialize Java object to JSON file. The Jackson’s ObjectMapper class provides writeValue(File, Object) and readValue(File, Class<T>) methods which allow us to write an object into JSON file and read JSON file into an object respectively.

package org.kodejava.jackson;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.kodejava.jackson.support.Artist;

import java.io.File;
import java.io.IOException;

public class ObjectToJsonFile {
    public static void main(String[] args) {
        Artist artist = new Artist();
        artist.setId(1L);
        artist.setName("The Beatles");

        ObjectMapper mapper = new ObjectMapper();

        File file = new File("artist.json");
        try {
            // Serialize Java object info JSON file.
            mapper.writeValue(file, artist);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            // Deserialize JSON file into Java object.
            Artist newArtist = mapper.readValue(file, Artist.class);
            System.out.println("newArtist.getId() = " + newArtist.getId());
            System.out.println("newArtist.getName() = " + newArtist.getName());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The result of the code snippet are:

newArtist.getId() = 1
newArtist.getName() = The Beatles

Maven Dependencies

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

Maven Central Maven Central Maven Central