CFL_Jeff
CFL_Jeff

Reputation: 2719

Can I configure Jackson JSON pretty printing from annotations or from Spring MVC controller?

I'm using Jackson 1.9.6 (codehaus) for JSON serialization of my response bodies in a Spring MVC application, and I'm having trouble finding a way to configure pretty printing. All of the code examples I've been able to find (like this and this) involve playing with an instantiation of ObjectMapper or ObjectWriter, but I don't currently use an instantiation of these for anything else. I wouldn't even know where to put this code. All of my Jackson configurations are taken care of by annotating the POJOs being serialized to JSON.

Is there a way to specify pretty printing in an annotation? I would think they would have put that in @JsonSerialize, but it doesn't look like it.

My class to be serialized looks like this:

@JsonAutoDetect
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class JSONObject implements Serializable{...}

and my Spring controller method looks like this:

@RequestMapping(method = RequestMethod.GET)
public @ResponseBody List<Object> getMessagesAndUpdates(HttpServletRequest request, HttpServletResponse response) {
    JSONObject jsonResponse = new JSONObject();
    .
    .
    .
    //this will generate a non-pretty-printed json response.  I want it to be pretty-printed.
    return jsonResponse;
}

Upvotes: 2

Views: 4792

Answers (2)

Matt Crysler
Matt Crysler

Reputation: 885

Adding this as a separate answer so I can format the output.

As luck would have it, the non-Spring Boot solution wasn't too far from the Spring Boot solution :)

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
    builder.indentOutput(true).dateFormat(new SimpleDateFormat("yyyy-MM-dd"));
    converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
    converters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build()));
}

Upvotes: 1

Matt Crysler
Matt Crysler

Reputation: 885

I searched and searched for something similar and the closest I could find was adding this bean to my Application context configuration (NOTE: I am using Spring Boot so I am not 100% certain this will work as-is in a non-Spring Boot app):

@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder()
{
    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
    builder.indentOutput(true);
    return builder;
}

In my opinion, its the cleanest available solution and works pretty well.

Upvotes: 5

Related Questions