How to Pretty Print Object in Java using Jackson
How can we pretty print a Java object using Jackson?
Suppose we have a static ObjectMapper
available.
public static final ObjectMapper OBJECT_MAPPER;
Using writerWithDefaultPrettyPrinter()
, we can construct an ObjectWriter
that serializes objects using the pretty printer for indentation.
public static <T> String prettyPrintObject(T obj) {
try {
return OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
} catch (JsonProcessingException e1) {
throw new RuntimeException(e1);
}
}
Prior to version 2.1, writeValueAsString()
could throw an IOException
.
In version 2.1, we can just handle JsonProcessingException
, which will throw a standard RunTimeException
.