JSON pretty print with... Spring Boot

I wrote a post a few months ago about a pretty-print hack for JAX-RS (http://vincentdevillers.blogspot.fr/2015/02/json-pretty-print-with-jax-rsjackson.html). Here is a version using Spring Boot. All the stuff is located in a @Configuration class extending WebMvcConfigurerAdapter:

import java.io.IOException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;

@Configuration
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {

@Autowired
private ObjectMapper mapper;

@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.replaceAll(c -> {
if (c instanceof MappingJackson2HttpMessageConverter) {

MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(mapper) {
protected void writePrefix(JsonGenerator generator, Object object) throws IOException {
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
if (attributes != null && attributes instanceof ServletRequestAttributes) {
String attribute = ((ServletRequestAttributes) attributes).getRequest().getParameter("pretty");
if (attribute != null) {
generator.setPrettyPrinter(new DefaultPrettyPrinter());
}
}
super.writePrefix(generator, object);
}
};
return converter;
} else {
return c;
}
});
}
}

Labels: , , , , ,