来自 Jackson 2.2 的 ObjectMapper 的漂亮打印 JSON [英] Pretty printing JSON from Jackson 2.2's ObjectMapper

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

问题描述

现在我有一个 org.fasterxml.jackson.databind.ObjectMapper 的实例,并想获得一个带有漂亮 JSON 的 String.我的谷歌搜索的所有结果都提出了 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("

----------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天全站免登陆