Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
668 views
in Technique[技术] by (71.8m points)

java - What is the simplest way to configure the indentation spacing on a 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?

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

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);

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

The output will be:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...