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.
ObjectMapper is the main actor class of Jackson library. ObjectMapper class ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model (JsonNode), as well as related functionality for performing conversions.
Yes, that is safe and recommended.
We can format a date using the setDateFormat() of ObjectMapper class. This method can be used for configuring the default DateFormat when serializing time values as Strings and deserializing from JSON Strings.
Jackson is a framework that provides the means to read and write objects to and from JSON. Typically, it tries to use built in support for common classes and simple types. It will also use a default serializer based on reflection to write the JSON, but will need some guidance for more complex custom objects.
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" ] }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With