本文介绍了我可以从批注或从Spring MVC控制器配置Jackson JSON漂亮打印吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jackson 1.9.6(codehaus)在Spring MVC应用程序中对响应主体进行JSON序列化,并且在寻找一种配置漂亮打印的方法时遇到了麻烦.我已经找到的所有代码示例(例如和)涉及实例化ObjectMapperObjectWriter,但是我目前没有将这些实例化用于其他任何事情.我什至不知道将这段代码放在哪里.通过注释要序列化为JSON的POJO,可以处理我所有的Jackson配置.

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.

是否可以在批注中指定漂亮的打印?我想他们会把它放在@JsonSerialize中,但是看起来不像这样.

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.

我要序列化的类如下:

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

我的Spring控制器方法如下:

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

推荐答案

我搜索并搜索了类似的东西,而我能找到的最接近的东西是将该bean添加到我的Application上下文配置中(注意:我正在使用Spring Boot,所以我不能100%地确定这将在非Spring Boot应用程序中按原样工作):

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.

这篇关于我可以从批注或从Spring MVC控制器配置Jackson JSON漂亮打印吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 18:44