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
Read more Gson examples
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.
Which Gson version?
Nice utility. Thanks for sharing!
Thank you
HI ,
can you pls tell me , how to compare two json responses or files in java
Try JSONAssert
https://www.mkyong.com/java/jsonassert-how-to-unit-test-json-data/
Muchas Gracias!! Me fue muy Util!!
Thanks!! it was very usefull for me
Very cool! There’s online tools like http://www.jsonprettyprint.net too where you can copy paste your raw JSON to pretty print it.
Simple and nice. thanks for sharing.
Really You are the one for Java Real way of explanation
Thank you. This saved me some time.