How to pretty print JSON with gson

Update (May, 2018): Sometimes your project already has a dependency to another mapping library and you don’t want to introduce a new one just for pretty printing a JSON. Thus I appended a short section for Jackson.

Pretty print with gson

Just a snippet of code: "How to create pretty printed JSON" with the google/gson library:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(bundleEntry);

For Gradle/Grails you might want to use:

compile 'com.google.code.gson:gson:2.8.2'

with Apache Maven:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
</dependency>

Pretty print with jackson

As promised the FasterXML/jackson version (code only):

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema);

The following is a nice example why I like code reviews and pair programming. I came up with a cumbersome version how to store a pretty JSON and the code was refined to:

Path path = schemaLocation.resolve("schema.json");

try (OutputStream out = Files.newOutputStream(path, CREATE)) {
    new ObjectMapper().writerWithDefaultPrettyPrinter().writeValue(out, schema);
}

Happy pretty printing.

Contributions welcome! We would be happy if you drop us a note with your code snippet in case your favourite mapping library is missing in the list.