在 Jackson ObjectMapper 上配置缩进间距的最简单方法是什么? [英] What is the simplest way to configure the indentation spacing on a Jackson ObjectMapper?

查看:83
本文介绍了在 Jackson ObjectMapper 上配置缩进间距的最简单方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的在为解决这个问题的复杂程度而苦苦挣扎.正如标题所说:创建带有 4 个空格 PrettyPrinter 的 Jackson ObjectMapper 的简单方法是什么?

I'm really struggling with the degree of complexity I am perceiving in solving this problem. As the title says: What is a simple way to create a Jackson ObjectMapper with a 4-space PrettyPrinter?

加分点:我如何修改现有 ObjectMapper 以使其漂亮地打印 4 个空格?

Bonus points: How can I modify an existing ObjectMapper to make it pretty print 4 spaces?

通过我的研究,我发现启用漂亮打印的最简单方法通常是在映射器上设置 INDENT_OUTPUT:

Through my research, I've found that the simplest way is to enable pretty printing generally is to set INDENT_OUTPUT on the mapper:

objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

然而,这仅启用了 DefaultPrettyPrinter,它有 2 个缩进空格.我想要 4. 要做到这一点,似乎我必须构建自己的 ObjectMapper,提供一个 JsonFactory 和一个 JsonGeneratorPrettyPrinter 有 4 个空格.对于在其他平台上如此简单的事情来说,这太过分了.请告诉我有更简单的方法.

However, this only enables the the DefaultPrettyPrinter, which has 2 spaces of indentation. I would like 4. To do this, it seems like I have to construct my own ObjectMapper, providing a JsonFactory with a JsonGenerator that has a PrettyPrinter that does 4 spaces. This is way too intense for something that is so so so simple on other platforms. Please tell me there is a simpler way.

推荐答案

我不确定这是否是最简单的方式,但是...您可以使用 ObjectMapper代码> 使用自定义打印机.如果您修改缩进行为,则可以使用 DefaultPrettyPrinter.

I am not sure if this is the simplest way to go but... You can use the ObjectMapper with a custom printer. The DefaultPrettyPrinter can be used if you modify the indent behaviour.

// Create the mapper
ObjectMapper mapper = new ObjectMapper();

// Setup a pretty printer with an indenter (indenter has 4 spaces in this case)
DefaultPrettyPrinter.Indenter indenter = 
        new DefaultIndenter("    ", DefaultIndenter.SYS_LF);
DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
printer.indentObjectsWith(indenter);
printer.indentArraysWith(indenter);

// Some object to serialize
Map<String, Object> value = new HashMap<>();
value.put("foo", Arrays.asList("a", "b", "c"));

// Serialize it using the custom printer
String json = mapper.writer(printer).writeValueAsString(value);

// Print it
System.out.println(json);

输出将是:

{
    "foo" : [
        "a",
        "b",
        "c"
    ]
}

这篇关于在 Jackson ObjectMapper 上配置缩进间距的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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