In this short article, you will learn how to pretty-print a JsonNode
object to a JSON string using the Jackson library.
Pretty print JsonNode
using toPrettyString()
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"
}
Pretty print JsonNode
using writerWithDefaultPrettyPrinter()
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 me on Twitter and LinkedIn. You can also subscribe to RSS Feed.