# How to pretty print JSON using Gson in Java

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Nov 30, 2019, updated Oct 14, 2022. Topics: Java, JSON.
Canonical URL: https://attacomsian.com/blog/gson-pretty-print-json

> A short tutorial to learn how to enable pretty print JSON output using Gson.

In this tutorial, you'll learn how to use [Gson](https://attacomsian.com/blog/gson-read-write-json) to enable pretty print JSON output. By default, Gson outputs the final JSON in compact format:

```java
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:

```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:

```java
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:

```json
{
  "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](https://attacomsian.com/blog/gson-read-write-json) tutorial.
