我正在使用 Jackson 1.9.6 (codehaus) 在 Spring MVC 应用程序中对响应主体进行 JSON 序列化,但我在寻找配置漂亮打印的方法时遇到了困难。我找到的所有代码示例(例如this https://stackoverflow.com/questions/6541757/when-using-spring-mvc-for-rest-how-do-you-enable-jackson-to-pretty-print-render and this https://stackoverflow.com/a/6339454/1245897)涉及玩的实例化ObjectMapper
or ObjectWriter
,但我目前不将它们的实例用于其他用途。我什至不知道该将代码放在哪里。我的所有 Jackson 配置都是通过注释被序列化为 JSON 的 POJO 来处理的。
有没有办法在注释中指定漂亮的打印?我认为他们会把它放在 @JsonSerialize 中,但它看起来不像。
我要序列化的类如下所示:
@JsonAutoDetect
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class JSONObject implements Serializable{...}
我的 Spring 控制器方法如下所示:
@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添加到我的应用程序上下文配置中(注意:我正在使用Spring Boot,所以我不能100%确定这会在非Spring Boot应用程序中按原样工作):
@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder()
{
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.indentOutput(true);
return builder;
}
在我看来,它是最干净的可用解决方案,而且效果很好。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)