Enable Pretty Print of JSON with Jackson
1 CommentJSON has become the most preferred way of transmitting data across network connections. JSON being easily readable by machines is one of the many reasons for JSON’s popularity. However, JSON unless formatted well, is not easily readable by a human. Pretty printing a JSON is one common operation to improve the readability of the JSON. Enabling pretty print for Jackson is easy when you are using Jackson on its own. Even easier when you are using Jackson with Spring Boot.
In this post, I will explain how to pretty print JSON using the Jackson library standalone, and the Spring configuration under Spring Boot.
The Maven POM
In order to use Jackson, you need the Jackson JAR files. If you are using Maven, include the Jackson dependencies in your Maven POM.
Here is the code to add the Jackson dependencies.
<!-- Jackson Dependencies--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency>
Note: When using Spring Boot, the Jackson dependencies are typically included under the Spring Boot starters.
The POJO
Let’s create a JsonPrettyPrintDemoBean
POJO with few fields that will be serialized to JSON.
The JsonPrettyPrintDemoBean POJO is this.
JsonPrettyPrintDemoBean.java
public class JsonPrettyPrintDemoBean { public long personId= 123L; publicString personName= "James Clark"; @JsonGetter(value = "person-id") public long getPersonId() { returnpersonId; } @JsonSetter("person-id") public void setPersonId(long personId) { this.personId= personId; } @JsonGetter(value = "person-name") publicString getPersonName() { returnpersonName; } @JsonSetter("person-name") public void setPersonName(String personName) { this.personName= personName; } @Override publicString toString() { return"JsonPrettyPrintDemoBean{" + "personId=" + personId+ ", personName='" + personName+ '\'' + '}'; } }
Pretty Print JSON Object
Let us serialize the JsonPrettyPrintDemoBean
POJO into JSON. A test class to test the serialization and print the serialized object is this.
. . public class JsonPrettyPrintDemoBeanTest { privateObjectMapperobjectMapper; @Before public void setUp() throws Exception{ objectMapper= new ObjectMapper(); } @After public void tearDown() throws Exception{ objectMapper= null; } @Test public void testJsonPrettyPrintObject() throws JsonProcessingException { /*JSON without pretty print*/ String jsonCompactString = objectMapper.writeValueAsString(new JsonPrettyPrintDemoBean()); System.out.println("JSON without pretty print"); System.out.println(jsonCompactString); assertThat(jsonCompactString, containsString("person-id")); assertThat(jsonCompactString, containsString("person-name")); } . . . }
The output of running the test is this.
JSON without pretty print {"person-id":123,"person-name":"James Clark"}
As you can notice in the preceding output, the JSON is compact. It is not formatted and therefore difficult to read. Imagine such output for a large number of properties. Lack of proper formatting makes it difficult to read or search the JSON for any particular key or value. To address this challenge, you can pretty print JSON.
To enable pretty printing, you need to call the writerWithDefaultPrettyPrinter()
on the ObjectMapper()
, like this.
/*JSON with pretty print*/ String jsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(new JsonPrettyPrintDemoBean()); System.out.println("JSON with pretty print"); System.out.println(jsonString); assertThat(jsonString, containsString("person-id")); assertThat(jsonString, containsString("person-name"));
With pretty printing, the output JSON is this.
JSON with pretty print { "person-id" : 123, "person-name" : "James Clark" }
Pretty Print JSON String
Let’s try to use writerWithDefaultPrettyPrinter()
with a JSON string with this code snippet.
String jsonString = "{\"person-id\": 231, \"person-name\": \"Mary Parker\"}"; /*JSON output in compact mode:*/ System.out.println("JSON without mapping to object"); System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonString));
The output printed is in compact mode and will be the same as the String input.
JSON without mapping to object "{\"person-id\": 231, \"person-name\": \"Mary Parker\"}"
To enable pretty printing, read the JSON string into an object. In our example, we can read the jsonString
into the JsonPrettyPrintDemoBean
POJO. Then, enable pretty printing, with a call the writerWithDefaultPrettyPrinter()
on the ObjectMapper
, like this.
/*Reading into POJO and pretty print*/ System.out.println("JSON mapping to POJO with pretty print"); JsonPrettyPrintDemoBean bean = objectMapper.readValue(jsonString, JsonPrettyPrintDemoBean.class); System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(bean));
The output is this.
JSON mapping to POJO with pretty print { "person-id" : 231, "person-name" : "Mary Parker" }
If you only need to pretty print a JSON string, you can use Object instead of creating an application POJO.
The code to do so is this.
/*Reading into Object and pretty print*/ Object object = objectMapper.readValue(jsonString, Object.class); System.out.println("JSON mapping to Object with pretty print"); System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object));
The output with pretty print is this.
JSON mapping to Object with pretty print { "person-id" : 231, "person-name" : "Mary Parker" }
The complete test code is this.
JsonPrettyPrintDemoBeanTest.java
The output of running the test in IntelliJ is this.
Pretty Printing Jackson with Spring Boot
A common use case for pretty printing JSON is in Spring RESTFul Web services. Such services expose endpoints that clients consume. Clients can be front-end applications using some HTTP library, a browser sending GET requests or a REST client such as Postman.
These clients make REST calls to the service and receive JSON data. At times, the clients might require presenting the data to users. Without pretty printing, the JSON returned by a Spring Boot REST service in Postman looks like this.
For a human-readable format, we need to enable JSON pretty printing.
With minimal changes, you can enable pretty printing in your Spring Boot application.
The most convenient method is to enable pretty printing in the application.properties
file, like this:
spring.jackson.serialization.indent_output=true
The second approach is to programmatically set the prettyPrint
field of MappingJackson2HttpMessageConverter
to true. To do so, create a configuration class in your application like this.
JacksonPrettyPrintConfiguration.java
package guru.springframework.blog.config; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import java.util.List; @Configuration public class JacksonPreetyPrintConfiguration extends WebMvcConfigurationSupport { @Override protected void extendMessageConverters( List<HttpMessageConverter<?>> converters ) { for ( HttpMessageConverter<?> converter : converters ) { if ( converter instanceof MappingJackson2HttpMessageConverter) { MappingJackson2HttpMessageConverter jacksonConverter = (MappingJackson2HttpMessageConverter) converter; jacksonConverter.setPrettyPrint( true ); } } } }
This configuration class extends WebMvcConfigurationSupport
and overrides the extendMessageConverters()
method. In this method, the setPrettyPrint()
method is called on the MappingJackson2HttpMessageConverter
object, passing true
as the parameter.
With pretty printing enabled, the JSON output in Postman is this.
You can download the example code from here.
Santi. S
Hi there,
I think there is a typo or things has changed a bit, using yaml config is:
indent-output instead of indent_output