Convert JSON String to Pretty Print JSON output using Jackson Convert JSON String to Pretty Print JSON output using Jackson java java

Convert JSON String to Pretty Print JSON output using Jackson


To indent any old JSON, just bind it as Object, like:

Object json = mapper.readValue(input, Object.class);

and then write it out with indentation:

String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);

this avoids your having to define actual POJO to map data to.

Or you can use JsonNode (JSON Tree) as well.


The simplest and also the most compact solution (for v2.3.3):

ObjectMapper mapper = new ObjectMapper();mapper.enable(SerializationFeature.INDENT_OUTPUT);mapper.writeValueAsString(obj)


The new way using Jackson 1.9+ is the following:

Object json = OBJECT_MAPPER.readValue(diffResponseJson, Object.class);String indented = OBJECT_MAPPER.writerWithDefaultPrettyPrinter()                               .writeValueAsString(json);

The output will be correctly formatted!