How do I make Jackson's build() method pretty-print its JSON output? Here is an example that pretty-prints the ugly form of JSON code. I need to take the nice version of
With the streaming API, you can use JsonGenerator.copyCurrentEvent() to easily re-output the token stream with whatever pretty-printing applied you want, including the default of no whitespace; this avoids buffering the entire document in memory and building a tree for the document.
// source and out can be streams, readers/writers, etc.
String source = " { \"hello\" : \" world \" } ";
StringWriter out = new StringWriter();
JsonFactory factory = new JsonFactory();
JsonParser parser = factory.createParser(source);
try (JsonGenerator gen = factory.createGenerator(out)) {
while (parser.nextToken() != null) {
gen.copyCurrentEvent(parser);
}
}
System.out.println(out.getBuffer().toString()); // {"hello":" world "}
You can use the same approach to pretty-print a JSON document in a streaming fashion:
// reindent
gen.setPrettyPrinter(new DefaultPrettyPrinter());