Spring in Practice

Willie Wheeler's Spring blog

How to Pretty Print Your JSON With Spring and Jackson

| Comments

When implementing RESTful web services using Spring Web MVC, by default Spring doesn’t pretty print the JSON output. Fortunately this is easy to address when using Java-based configuration. Here’s how, using Jackson 2.

public class MyAppConfig extends WebMvcConfigurerAdapter {

    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
        converters.add(new ByteArrayHttpMessageConverter());
        converters.add(new ResourceHttpMessageConverter());
        converters.add(new SourceHttpMessageConverter<Source>());
        converters.add(new AllEncompassingFormHttpMessageConverter());

    public MappingJackson2HttpMessageConverter jackson2Converter() {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        return converter;

    public ObjectMapper objectMapper() {
        Object objectMapper = new ObjectMapper();
        return objectMapper;

Here we can see a key advantage of using Java-based configuration, which is that we can easily call the ObjectMapper.enable() method, allowing us to activate pretty printing.