Enable Pretty Print of JSON with Jackson

Enable Pretty Print of JSON with Jackson

1 Comment

Last Updated on October 15, 2024 by jt

JSON has become the most preferred way of transmitting data across network connections. JSON being easily readable by machines is one of the many reasons for JSON’s popularity. However, JSON unless formatted well, is not easily readable by a human. Pretty printing a JSON is one common operation to improve the readability of the JSON. Enabling pretty print for Jackson is easy when you are using Jackson on its own. Even easier when you are using Jackson with Spring Boot.

In this post, I will explain how to pretty print JSON using the Jackson library standalone, and the Spring configuration under Spring Boot.

The Maven POM

In order to use Jackson, you need the Jackson JAR files. If you are using Maven, include the Jackson dependencies in your Maven POM.

Here is the code to add the Jackson dependencies.

<!-- Jackson Dependencies-->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>${jackson.version}</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>${jackson.version}</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${jackson.version}</version>
</dependency>

Note: When using Spring Boot, the Jackson dependencies are typically included under the Spring Boot starters.

The POJO

Let’s create a JsonPrettyPrintDemoBean POJO with few fields that will be serialized to JSON.

The JsonPrettyPrintDemoBean POJO is this.

JsonPrettyPrintDemoBean.java
public class JsonPrettyPrintDemoBean {
public long personId= 123L;
publicString  personName= "James Clark";

  @JsonGetter(value = "person-id")
  public long getPersonId() {
    returnpersonId;
  }
  @JsonSetter("person-id")
  public void setPersonId(long personId) {
    this.personId= personId;
  }
  @JsonGetter(value = "person-name")
  publicString getPersonName() {
    returnpersonName;
  }
  @JsonSetter("person-name")
  public void setPersonName(String personName) {
    this.personName= personName;
  }
  @Override
  publicString toString() {
    return"JsonPrettyPrintDemoBean{" +
      "personId=" + personId+
      ", personName='" + personName+ '\'' +
    '}';
  }
}

Pretty Print JSON Object

Let us serialize the JsonPrettyPrintDemoBean POJO into JSON. A test class to test the serialization and print the serialized object is this.

. . 
public class JsonPrettyPrintDemoBeanTest {
  privateObjectMapperobjectMapper;
  @Before
  public void setUp() throws Exception{
    objectMapper= new ObjectMapper();
  }
  @After
  public void tearDown() throws Exception{
    objectMapper= null;
  }
  @Test
  public void testJsonPrettyPrintObject() throws JsonProcessingException {
    /*JSON without pretty print*/
    String jsonCompactString = objectMapper.writeValueAsString(new 
    JsonPrettyPrintDemoBean());
    System.out.println("JSON without pretty print");
    System.out.println(jsonCompactString);
    assertThat(jsonCompactString, containsString("person-id"));
    assertThat(jsonCompactString, containsString("person-name"));
  }
. . .

}

The output of running the test is this.

 JSON without pretty print
{"person-id":123,"person-name":"James Clark"}

As you can notice in the preceding output, the JSON is compact. It is not formatted and therefore difficult to read. Imagine such output for a large number of properties. Lack of proper formatting makes it difficult to read or search the JSON for any particular key or value. To address this challenge, you can pretty print JSON.

To enable pretty printing, you need to call the writerWithDefaultPrettyPrinter() on the ObjectMapper(), like this.

/*JSON with pretty print*/
String jsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(new 
  JsonPrettyPrintDemoBean());
System.out.println("JSON with pretty print");
System.out.println(jsonString);
assertThat(jsonString, containsString("person-id"));
assertThat(jsonString, containsString("person-name"));

With pretty printing, the output JSON is this.

 JSON with pretty print
{
"person-id" : 123,
"person-name" : "James Clark"
}

Pretty Print JSON String with Jackson

Let’s try to use writerWithDefaultPrettyPrinter() with a JSON string with this code snippet.

String jsonString = "{\"person-id\": 231, \"person-name\": \"Mary Parker\"}";
/*JSON output in compact mode:*/
System.out.println("JSON without mapping to object");
System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonString));

The output printed is in compact mode and will be the same as the String input.

 JSON without mapping to object
"{\"person-id\": 231, \"person-name\": \"Mary Parker\"}"

To enable pretty printing, read the JSON string into an object. In our example, we can read the jsonString into the JsonPrettyPrintDemoBean POJO. Then, enable pretty printing, with a call the writerWithDefaultPrettyPrinter() on the ObjectMapper, like this.

/*Reading into POJO and pretty print*/
System.out.println("JSON  mapping to POJO with pretty print");
JsonPrettyPrintDemoBean bean = objectMapper.readValue(jsonString, JsonPrettyPrintDemoBean.class);
System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(bean));

The output is this.

 JSON mapping to POJO with pretty print
{
"person-id" : 231,
"person-name" : "Mary Parker"
}

If you only need to pretty print a JSON string, you can use Object instead of creating an application POJO.

The code to do so is this.

/*Reading into Object and pretty print*/
Object object = objectMapper.readValue(jsonString, Object.class);
System.out.println("JSON  mapping to Object with pretty print");
System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object));

The output with pretty print is this.

 JSON mapping to Object with pretty print
{
  "person-id" : 231,
  "person-name" : "Mary Parker"
}

The output of running the test in IntelliJ is this.

Output of running the test class in IntelliJ

Enabling Global Pretty Print for JSON with Jackson

To format JSON data in a more readable way using Jackson, you can globally enable the pretty print feature. This is particularly useful for developers who prefer neatly structured JSON outputs for logs or console displays.

This configuration will apply to the instance of the created ObjectMapper.

In this example, we enable the SerializationFeature.INDENT_OUTPUT

 @Test
    public void testGlobal() throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

        Person person = new Person();
        person.setPersonId(1L);
        person.setPersonName("John Doe");

        System.out.println(objectMapper.writeValueAsString(person));
    }

Here is the output from the above method:

{
  "person-id" : 1,
  "person-name" : "John Doe"
}

Pretty Printing Jackson with Spring Boot

A common use case for pretty printing JSON is in Spring RESTFul Web services. Such services expose endpoints that clients consume. Clients can be front-end applications using some HTTP library, a browser sending GET requests or a REST client such as Postman.

Raw JSON from Jackson under Spring Boot in Postman

These clients make REST calls to the service and receive JSON data. At times, the clients might require presenting the data to users. Without pretty printing, the JSON returned by a Spring Boot REST service in Postman looks like the above.

For a human-readable format, we need to enable JSON pretty printing.

With minimal changes, you can enable pretty printing in your Spring Boot application.

Unlike the above examples, where we are creating a Jackson ObjectMapper, Spring Boot’s auto-configuration when Jackson is detected on the classpath, will create and configure an instance of Jackson’s ObjectMapper in the Spring Context. In our Spring Managed Beans, we can simply ask for Spring to inject the auto-configured Jackson ObjectMapper.

Configuration of the Spring Managed ObjectMapper can be changed using application properties. The most convenient method is to enable pretty printing in the application.properties file, like this:

spring.jackson.serialization.indent_output=true

The second approach is to programmatically set the prettyPrint
field of MappingJackson2HttpMessageConverter to true. To do so, create a configuration class in your application like this.

JacksonPrettyPrintConfiguration.java
package guru.springframework.blog.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;

@Configuration
public class JacksonPreetyPrintConfiguration extends WebMvcConfigurationSupport {
    @Override
    protected void extendMessageConverters( List<HttpMessageConverter<?>> converters ) {

        for ( HttpMessageConverter<?> converter : converters ) {

            if ( converter instanceof MappingJackson2HttpMessageConverter) {

                MappingJackson2HttpMessageConverter jacksonConverter = (MappingJackson2HttpMessageConverter) converter;

                jacksonConverter.setPrettyPrint( true );

            }

        }

    }
}

This configuration class extends WebMvcConfigurationSupport and overrides the extendMessageConverters() method. In this method, the setPrettyPrint() method is called on the MappingJackson2HttpMessageConverter object, passing true as the parameter.

pretty print JSON from Jackson with Spring Boot

With pretty printing enabled, the JSON output in Postman is this.

You can download the example code for the JSON examples from Github here.

Conclusion

There are several ways to enable Jackson to pretty print JSON. This does make JSON much easier to read. Typically this feature is disabled. Using Pretty Print with JSON adds additional characters for the line breaks to your JSON payloads, thus creates larger overall payloads.

While this additional cost is trivial on the examples used in this post, they will add up on larger payloads and heavier workloads. For production workloads, enabling the pretty print of JSON is typically avoided. You normally only wish to do this for development and debugging.

About jt

    You May Also Like

    One comment

    1. May 22, 2019 at 10:30 am

      Hi there,
      I think there is a typo or things has changed a bit, using yaml config is:
      indent-output instead of indent_output

      Reply

    Leave a Reply

    Your email address will not be published. Required fields are marked *

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