How to pretty print JSON using Gson

This article shows how to pretty print JSON using Gson.

Table of contents:

P.S Tested with Gson 2.10.1

1. Setup Google Gson

Declare gson in the pom.xml.

pom.xml

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

2. Default Compact Print JSON

By default, Gson prints the JSON output in compact mode.

GsonPrettyPrintExample.java

package com.mkyong.json.gson;

import com.google.gson.Gson;

public class GsonPrettyPrintExample {

    public static void main(String[] args) {

        Gson gson = new Gson();

        String[] lang = {"Java", "Node", "Kotlin", "JavaScript"};

        String json = gson.toJson(lang);

        System.out.println(json);
        
    }
}

Output


["Java","Node","Kotlin","JavaScript"]

3. Pretty Print JSON using Gson

We can use the GsonBuilder to enable the pretty print JSON output.

GsonPrettyPrintExample.java

package com.mkyong.json.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonPrettyPrintExample {

    public static void main(String[] args) {

        // Gson gson = new Gson();

        // Create a GsonBuilder and enable the pretty print
        Gson gson = new GsonBuilder().setPrettyPrinting().create();

        String[] lang = {"Java", "Node", "Kotlin", "JavaScript"};

        String json = gson.toJson(lang);

        System.out.println(json);

    }
}

Output


[
  "Java",
  "Node",
  "Kotlin",
  "JavaScript"
]

4. Download Source Code

$ git clone https://github.com/mkyong/java-json

$ cd gson

5. References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments