Pretty printing JSON from Jackson 2.2's ObjectMapper

Anthony Atkinson picture Anthony Atkinson · Jul 12, 2013 · Viewed 123.5k times · Source

Right now I have an instance of org.fasterxml.jackson.databind.ObjectMapper and would like to get a String with pretty JSON. All of the results of my Google searches have come up with Jackson 1.x ways of doing this and I can't seem to find the proper, non-deprecated way of doing this with 2.2. Even though I don't believe that code is absolutely necessary for this question, here's what I have right now:

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
System.out.println("\n\n----------REQUEST-----------");
StringWriter sw = new StringWriter();
mapper.writeValue(sw, jsonObject);
// Want pretty version of sw.toString() here

Answer

gregwhitaker picture gregwhitaker · Jul 12, 2013

You can enable pretty-printing by setting the SerializationFeature.INDENT_OUTPUT on your ObjectMapper like so:

mapper.enable(SerializationFeature.INDENT_OUTPUT);