In tutorial, we show you how to enable pretty print JSON output in Gson framework. In last Gson – object to/from json example :
Gson gson = new Gson();
String json = gson.toJson(obj);
System.out.println(json);
the JSON output is display as compact mode like following :
{"data1":100,"data2":"hello","list":["String 1","String 2","String 3"]}
To enable pretty print, you should use GsonBuilder
return a Gson
object :
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(obj);
System.out.println(json);
Output
{ "data1": 100, "data2": "hello", "list": [ "String 1", "String 2", "String 3" ] }
See full example.
package com.mkyong.core;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class GsonExample {
public static void main(String[] args) {
DataObject obj = new DataObject();
// Gson gson = new Gson();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(obj);
System.out.println(json);
}
}