How to prettify a JSON in java?

Issue

I’m using ObjectMapper from Jackson, how can I convert an object into a pretty kson ?

Solution

You can do it by enabling INDENT_OUTPUT feature. This is a good option if you want to enable pretty print for all strings generated with the object mapper

ObjectMapper objectMapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
String prettyJson = objectMapper.writeValueAsString(object);

In alternative you can use the object mapper default pretty printer, in case you want to use the same object mapper for non-pretty jsons as well

ObjectMapper objectMapper = new ObjectMapper();
String prettyJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);