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 CentralMaven CentralMaven Central

Wayan

6 Comments

    • Hi Leonardo,

      To convert JSON to Array you code do something like:

      String jsonArray = "[{\"title\":\"Java in Action\"}, {\"title\":\"Spring in Action\"}]";
      
      ObjectMapper objectMapper = new ObjectMapper();
      try {
          Book[] books = objectMapper.readValue(jsonArray, Book[].class);
          for (Book book : books) {
              System.out.println(book);
          }
      } catch (IOException e) {
          e.printStackTrace();
      }
      
      Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.