How to pretty print JSON using Gson in Java

In this tutorial, you'll learn how to use Gson to enable pretty print JSON output. 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}

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 a Gson instance with pretty-printing
    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 what 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 me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.