In this tutorial, you'll learn how to use Gson to enable pretty print JSON output.

Default Gson Behavior

By default, Gson outputs the final JSON in compact format:

try {
    // create user object
    User user = new User("John Doe", "john.doe@example.com",
            new String[]{"Member", "Admin"}, true);

    // convert user object to JSON
    String json = new Gson().toJson(user);

    // print JSON string
    System.out.println(json);

} catch (Exception ex) {
    ex.printStackTrace();
}

The above code will generate the following compact-print JSON:

{"name":"John Doe","email":"john.doe@example.com","roles":["Member","Admin"],"admin":true}

Pretty Print JSON Output

To enable JSON pretty-print, you need the Gson object using GsonBuilder and call the setPrettyPrinting() method, as shown below:

try {
    // create user object
    User user = new User("John Doe", "john.doe@example.com",
            new String[]{"Member", "Admin"}, true);

    // create Gson instance with pretty-print
    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    // convert user object to pretty print JSON
    String json = gson.toJson(user);

    // print JSON string
    System.out.println(json);

} catch (Exception ex) {
    ex.printStackTrace();
}

Now here is how the final pretty-print JSON looks like:

{
  "name": "John Doe",
  "email": "john.doe@example.com",
  "roles": [
    "Member",
    "Admin"
  ],
  "admin": true
}

For more Gson examples, check out the How to read and write JSON using Gson in Java tutorial.

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Buy me a coffee (cost $3)

Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.