问题描述
我真的在努力解决我在解决这个问题时所感受到的复杂程度。正如标题所说:使用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
一个 JsonGenerator
,它有一个 PrettyPrinter
,它有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上配置缩进间距的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!