In this short article, you'll learn how to use Jackson to enable pretty print JSON output.

Default Jackson Behavior

By default, Jackson outputs the final JSON in compact format:

try {
    // create user object
    User user = new User("John Doe", "john.doe@example.com",
            new String[]{"Member", "Admin"}, true);

    // convert user object to JSON
    String json = new ObjectMapper().writeValueAsString(user);

    // print JSON string
    System.out.println(json);

} catch (Exception ex) {
    ex.printStackTrace();
}

Here is how the generated JSON looks like:

{"name":"John Doe","email":"john.doe@example.com","roles":["Member","Admin"],"admin":true}

Pretty Print JSON Output

To enable the pretty print JSON output while serializing a Java Object, you can use the writerWithDefaultPrettyPrinter() method of ObjectMapper:

try {
    // create user object
    User user = new User("John Doe", "john.doe@example.com",
            new String[]{"Member", "Admin"}, true);

    // create object mapper instance
    ObjectMapper mapper = new ObjectMapper();

    // convert user object to pretty print JSON
    String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);

    // print JSON string
    System.out.println(json);

} catch (Exception ex) {
    ex.printStackTrace();
}

Now here is how the final pretty print JSON looks like:

{
  "name" : "John Doe",
  "email" : "john.doe@example.com",
  "roles" : [ "Member", "Admin" ],
  "admin" : true
}

You can also enable the pretty print JSON output globally by using the DefaultPrettyPrinter class, as shown below:

try {
    // create user object
    User user = new User("John Doe", "john.doe@example.com",
            new String[]{"Member", "Admin"}, true);

    // create object mapper instance
    ObjectMapper mapper = new ObjectMapper();

    // create an instance of DefaultPrettyPrinter
    ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());

    // convert user object to pretty print JSON
    String json = writer.writeValueAsString(user);

    // print JSON string
    System.out.println(json);

} catch (Exception ex) {
    ex.printStackTrace();
}

For more Jackson examples, check out the How to read and write JSON using Jackson in Java tutorial.

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Buy me a coffee (cost $3)

Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.