Gson Pretty Print JSON example shows how to set the output to the pretty print mode in Java. By default, the Gson prints output in a compact format that removes all whitespaces, and pretty print is disabled, but it can be enabled very easily.
How to enable pretty print output in Gson?
The default value of the pretty print output is disabled as we can see in the below given example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package com.javacodeexamples.gsonexamples; import com.google.gson.Gson; public class GsonPrettyPrintExample { public static void main(String[] args) { String[] employees = new String[] {"Mark", "Alex", "John"}; Gson gsonObject = new Gson(); String json = gsonObject.toJson(employees); System.out.println(json); } } |
Output
1 |
["Mark","Alex","John"] |
The output becomes unreadable when we are dealing with large data in the default compact output format. To enable the pretty print output, we need to create the Gson object using the GsonBuilder class instead of using the constructor of the Gson class.
We can use the setPrettyPrinting
method of the GsonBuilder class to set it to true. Once we do that, we can create an object of the Gson class using the create
method as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package com.javacodeexamples.gsonexamples; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class GsonPrettyPrintExample { public static void main(String[] args) { String[] employees = new String[] {"Mark", "Alex", "John"}; /* * Instead of using the constructor * of the Gson class, use the GsonBuilder * class to create a Gson object. * * Also, call the setPrettyPrinting method * before calling the create method. */ Gson gsonObject = new GsonBuilder() .setPrettyPrinting() .create(); String json = gsonObject.toJson(employees); System.out.println(json); } } |
Output
1 2 3 4 5 |
[ "Mark", "Alex", "John" ] |
As you can see from the output, pretty printing is enabled now.
Please let me know your views in the comments section below.