Main Tutorials

Gson – How to enable pretty print JSON output

In this tutorial, we will show you how to enable JSON pretty print in Gson framework.

1. By default, Gson compact-print the JSON output :

GsonExample1.java

package com.mkyong;

import com.google.gson.Gson;

public class GsonExample1 {

    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"]

2. To enable JSON pretty-print, create Gson object with GsonBuilder

GsonExample2.java

package com.mkyong;

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

public class GsonExample2 {

    public static void main(String[] args) {

        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"
]
Note
Read more Gson examples

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
11 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
sng
7 years ago

Using gson.toJson(someObj) and new GsonBuilder().setPrettyPrinting().create() does not provide any difference result to me. My both the results are something like “{“name”:”mkyong”,”age”:35,”position”:”Founder”,”salary”:10000,”skills”:[“java”,”python”,”shell”]}”. Could some one help me in getting the correct format.

GOWRI SANKAR
9 years ago

Nice utility. Thanks for sharing!

Eswar
2 years ago

Thank you

pavan
5 years ago

HI ,

can you pls tell me , how to compare two json responses or files in java

Orlando PY
7 years ago

Muchas Gracias!! Me fue muy Util!!
Thanks!! it was very usefull for me

Peter McKenna
9 years ago

Very cool! There’s online tools like http://www.jsonprettyprint.net too where you can copy paste your raw JSON to pretty print it.

mkyong
7 years ago
Reply to  Peter McKenna

Simple and nice. thanks for sharing.

Ram
9 years ago

Really You are the one for Java Real way of explanation

Boris
10 years ago

Thank you. This saved me some time.