Pretty Formatted JSON in Spring Web MVC

I'm focused on the REST APIs in my Spring-Data MVC App at the moment and less on doing anything with the data in the Presentation Layer, so I'm generating a lot of JSON. And even though it's just mostly for testing, I want it to be pretty in my browser, like so.

The Jayway JsonPath Dependencies

First step is to add the com.jayway.json-path dependencies shown below. You can find them at Maven Central.

Configure Message Converter

Next we override the configureMessageConverters() method in our Spring Web Context Configuration class that extends WebMvcConfigurerAdapter.

public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        final ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        converter.setObjectMapper(objectMapper);
        converters.add(converter);
        super.configureMessageConverters(converters);
    }

And we got pretty JSON in our browser!

Source code discussed here is available in my Spring-Data MVC App on GitHub, branch v0.1.2.

Posted June 09, 2015 12:41 PM EDT

More Like This Post