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

天涯浪子 提交于 2019-12-24 00:34:56

问题


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;
}

回答1:


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.




回答2:


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()));
}


来源:https://stackoverflow.com/questions/14878890/can-i-configure-jackson-json-pretty-printing-from-annotations-or-from-spring-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!