从Jackson 2.2的ObjectMapper中打印JSON [英] Pretty printing JSON from Jackson 2.2's ObjectMapper

查看:217
本文介绍了从Jackson 2.2的ObjectMapper中打印JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我有一个 org.fasterxml.jackson.databind.ObjectMapper 的实例,想得到一个 String 使用漂亮的JSON。我的谷歌搜索的所有结果都提出了Jackson 1.x这样做的方法,我似乎无法找到适当的,不推荐使用2.2的方法。即使我不相信代码对于这个问题是绝对必要的,这就是我现在所拥有的:

Right now I have an instance of org.fasterxml.jackson.databind.ObjectMapper and would like to get a String with pretty JSON. All of the results of my Google searches have come up with Jackson 1.x ways of doing this and I can't seem to find the proper, non-deprecated way of doing this with 2.2. Even though I don't believe that code is absolutely necessary for this question, here's what I have right now:

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
System.out.println("\n\n----------REQUEST-----------");
StringWriter sw = new StringWriter();
mapper.writeValue(sw, jsonObject);
// Want pretty version of sw.toString() here


推荐答案

您可以通过在 ObjectMapper 上设置 SerializationFeature.INDENT_OUTPUT 来启用漂亮打印,如下所示:

You can enable pretty-printing by setting the SerializationFeature.INDENT_OUTPUT on your ObjectMapper like so:

mapper.enable(SerializationFeature.INDENT_OUTPUT);

这篇关于从Jackson 2.2的ObjectMapper中打印JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆