Last Updated on 28 October 2023   |   Print Email
You know, when developing REST APIs with Java and Spring framework, the JSON output in API response is not formatted (un-indented) by default, for example:Although this has no issue with JSON parsers, it’s difficult for human (programmers/API developers) to read and understand the API response directly in a web browser or terminal (command line). I think it’d be better to have the JSON output formatted (prettified) at the application level, for the convenient of API developers and consumers.So, how to prettify the JSON output in API response with Spring Boot?Well, Spring MVC integrates tightly with Jackson/FasterXML - the Java library for JSON - via an ObjectMapperthat does the serialization and deserialization from Java objects to JSON and vice-versa. So we just need to override the default by configuring the ObjectMapper directly via a Spring Bean in the main class as follows:
package net.codejava;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
...
@SpringBootApplication
public class RestApiApplication {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
return objectMapper;
}
public static void main(String[] args) {
SpringApplication.run(RestApiApplication.class, args);
}
}
Then you will see the JSON in API response is indented/formatted as shown in web browser below:And in terminal/command prompt:
You can also configure the ObjectMapper object in a separate Spring configuration class, as shown in the below example:
package net.codejava;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
@Configuration
public class AppConfig {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
return objectMapper;
}
}
However, this won’t work with unit tests for controller layer using @WebMvcTest annotation that doesn’t load configuration classes.That’s a simple way to prettify JSON output in REST API development with Spring framework and Jackson library, at the application level. I hope you find this post helpful.You can also watch the following video to see the coding in action:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.