Pretty-Printing JSON with Jackson in Java and Spring Boot

Jackson is one of the most common libraries for working with serialization and deserialization in Java and Spring Boot, primarily used for parsing and converting between POJOs and JSON.

Though, if you’ve worked with Jackson, you’ll notice a distinct lack of pretty-printing by default:

{Task 1=In_Progress, Task 2=Done, Task 3=Planned}

In this short tutorial, you’ll learn how to pretty-print JSON with Jackson in standard Java and with Spring Boot.

We’ll be working with a JSON string, and a POJO converted into a JSON string, since these behave differently:

public class Book {
    private String title;
    private String author;
    private int releaseYear;

    public Book(String title, String author, int releaseYear) {
        this.title = title;
        this.author = author;
        this.releaseYear = releaseYear;
    }
    

Let’s instantiate a Book instance, and a string for the input:

String inputString = "{n" +
        ""Task 1" : "In_Progress",n" +
        ""Task 2" : "Done",n" +
        ""Task 3" : "Planned"n" +
        "}";

Book book = new Book("Our Mathematical Universe", "Max Tegmark", 2014);

Pretty-Print JSON with Jackson Once

If you’d like to simply pretty-print once, in a single call, rather than setting the global printing flag – you can simply use the writerWithDefaultPrettyPrinter() call before writing a value as a string:

ObjectMapper mapper = new ObjectMapper();

Object jsonString = mapper.readValue(inputString, Object.class);
String indentedString = mapper.writerWithDefaultPrettyPrinter()
                              .writeValueAsString(jsonString);
        
        
System.out.println(jsonString);
System.out.println(indentedString);

The input string was read from (JSON-to-Object), and the value of this object was written back into a string, using pretty-printing (Object-to-JSON):

{Task 1=In_Progress, Task 2=Done, Task 3=Planned}

{
  "Task 1" : "In_Progress",
  "Task 2" : "Done",
  "Task 3" : "Planned"
}

Alternatively, when using readTree(), the resulting JsonNode has a toPrettyString() function that serves as a great simple way to convert strings to pretty-printed JSON:

ObjectMapper mapper = new ObjectMapper();
Object jsonString = mapper.readTree(inputString).toPrettyString();
System.out.println(jsonString);

This is a quick and simple way to format an input JSON string! When working with POJOs, instead of reading from a given input, we’ll only perform Object-to-JSON conversion and enable pretty-printing:

ObjectMapper mapper = new ObjectMapper();

String jsonBook = mapper.writeValueAsString(book);
String indentedBook = mapper.writerWithDefaultPrettyPrinter()
                            .writeValueAsString(book);


System.out.println(jsonBook);
System.out.println(indentedBook);
{"title":"Our Mathematical Universe","author":"Max Tegmark","releaseYear":2014}
{
  "title" : "Our Mathematical Universe",
  "author" : "Max Tegmark",
  "releaseYear" : 2014
}

Global Pretty-Print Setting

Alternatively, you can enable global pretty-printing, if that’s the preferable global behavior of Jackson for your project. This is as easy as using the enable() method of the ObjectMapper() instance when you’re instantiating it:

ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);

As soon as you write an object as a JSON string – pretty-printing will be enabled by default:

Object jsonString = mapper.readValue(inputString, Object.class);
String indentedString = mapper.writeValueAsString(jsonString);

System.out.println(jsonString);
System.out.println(indentedString);

This results in:

{Task 1=In_Progress, Task 2=Done, Task 3=Planned}
{
  "Task 1" : "In_Progress",
  "Task 2" : "Done",
  "Task 3" : "Planned"
}

With POJOs:

String jsonBook = mapper.writeValueAsString(book);
System.out.println(jsonBook);

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

{
  "title" : "Our Mathematical Universe",
  "author" : "Max Tegmark",
  "releaseYear" : 2014
}

This approach is significantly less verbose if pretty-printing is a common display format.

Pretty-Printing Jackson with Spring Boot

If you’re using Spring Boot, without a manual ObjectMapper instance being created and rely on the underlying serializer, you can set the indent_output flag to true in the application.properties file:

spring.jackson.serialization.indent_output=true

Or, in application.yaml:

spring:
  jackson:
    serialization:
      INDENT_OUTPUT: true

This sets the SerializationFeature.INDENT_OUTPUT flag in Spring’s ObjectMapper instance.

Conclusion

In this short tutorial, we’ve taken a look at how you can pretty-print JSON from a String or POJO using Jackson. We’ve explored single-print changes (when you only want to pretty-print once) and setting the global Jackson flag for ObjectMapper. Finally, we took a look at changing Spring Boot properties for enabling pretty printing with Jackson.

Time Stamp:

More from Stackabuse