In Jackson, we can use writerWithDefaultPrettyPrinter()
to pretty print the JSON output.
Tested with Jackson 2.9.8
1. Pretty Print JSON
1.1 By default, Jackson print in compact format:
ObjectMapper mapper = new ObjectMapper(); Staff staff = createStaff(); String json = mapper.writeValueAsString(staff); System.out.println(json);
Output
{"name":"favtuts","age":38,"skills":["java","python","node","kotlin"]}
1.2 To enable pretty print on demand.
ObjectMapper mapper = new ObjectMapper(); Staff staff = createStaff(); // pretty print String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff); System.out.println(json);
Output
{
"name" : "favtuts",
"age" : 38,
"skills" : [ "java", "python", "node", "kotlin" ]
}
1.3 To enable pretty print globally.
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; // pretty print ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); Staff staff = createStaff(); String json = mapper.writeValueAsString(staff); System.out.println(json);
Output
{
"name" : "favtuts",
"age" : 38,
"skills" : [ "java", "python", "node", "kotlin" ]
}
Note
To display the pretty print JSON output on an HTML page, wraps it with
pre
tags.
<pre>${pretty-print-json-output}</pre>
Note – 12/12/2013
The article is updated to use
writerWithDefaultPrettyPrinter()
, the olddefaultPrettyPrintingWriter()
is deprecated.