Is there functionality to pretty print/format JSON in Java SDK 2.0?


#1

During debugging, it’s useful to trace out JSON documents, but “toString()” reports it all on one line.

Is there a way to pretty-print or format JsonObject objects in the Java SDK v2.0?


#2

Not directly, but you can use the Jackson ObjectMapper that is used internally (it has a module to deal with JsonObject):

JsonObject obj = JsonObject.create().put("test", "value").put("test2", true);
System.out.println(obj);

try {
    System.out.println("\n" + JacksonTransformers.MAPPER
        .writerWithDefaultPrettyPrinter() //this will do pretty print
        .writeValueAsString(obj));
} catch (JsonProcessingException e) {
    e.printStackTrace();
}

Prints:

{"test":"value","test2":true}

{
  "test" : "value",
  "test2" : true
}