In this short article, you will learn how to pretty print a JsonNode object to a JSON string by using the Jackson library.

Using toPrettyString() Method

The simplest and straightforward way to pretty print JsonNode is using the toPrettyString() method, as shown below:

try {
    // JSON string
    String json = "{\"name\":\"John Doe\",\"email\":\"john.doe@example.com\"," +
            "\"roles\":[\"Member\",\"Admin\"],\"admin\":true,\"city\"" +
            ":\"New York City\",\"country\":\"United States\"}";

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

    // convert JSON string to `JsonNode`
    JsonNode node = mapper.readTree(json);

    // `JsonNode` to JSON string
    String prettyString = node.toPrettyString();

    // print pretty JSON string
    System.out.println(prettyString);

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

The above example code will output the following pretty print JSON:

{
  "name" : "John Doe",
  "email" : "john.doe@example.com",
  "roles" : [ "Member", "Admin" ],
  "admin" : true,
  "city" : "New York City",
  "country" : "United States"
}

Using writerWithDefaultPrettyPrinter() Method

Another way of pretty printing JsonNode is to use the ObjectMapper class writerWithDefaultPrettyPrinter() method:

try {
    // JSON string
    String json = "{\"name\":\"John Doe\",\"email\":\"john.doe@example.com\"," +
            "\"roles\":[\"Member\",\"Admin\"],\"admin\":true,\"city\"" +
            ":\"New York City\",\"country\":\"United States\"}";

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

    // convert JSON string to `JsonNode`
    JsonNode node = mapper.readTree(json);

    // `JsonNode` to JSON string
    String prettyString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(node);

    // print pretty JSON string
    System.out.println(prettyString);

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

Here is the output of the above example code:

{
  "name" : "John Doe",
  "email" : "john.doe@example.com",
  "roles" : [ "Member", "Admin" ],
  "admin" : true,
  "city" : "New York City",
  "country" : "United States"
}

Read the guide Working with Tree Model Nodes in Jackson for more JsonNode examples.

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.