Gson – Pretty Print JSON

By default, Gson prints the JSON in a compact format. It means there will not be any whitespace in between field names and their value, object fields, and objects within arrays in the JSON output etc.

1. GsonBuilder.setPrettyPrinting()

To enable the Gson Pretty Print feature, we must configure the Gson instance using the GsonBuilder. Then use setPrettyPrinting() method to enable it.

Note that, by default, Gson formats the output JSON with a default line length of 80 characters, 2-character indentation, and 4-character right margin.

Gson gson = new GsonBuilder()
				.setPrettyPrinting()
				.create();

String jsonOutput = gson.toJson(someObject);

2. Demo

Java program to serialize an Employee object and pretty print the JSON output.

public class Employee
{
	private Integer id;
    private String firstName;
    private String lastName;
    private String email;

    //Constructors
    //Getters and setters
}
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class Main
{
	public static void main(String[] args)
    {
		Employee employeeObj = new Employee(1, "Lokesh", "Gupta", "howtogoinjava@gmail.com");

		Gson gson = new GsonBuilder()
				.setPrettyPrinting()
				.create(); 

		System.out.println(gson.toJson(employeeObj));
    }
}

Program output.

{
  "id": 1,
  "firstName": "Lokesh",
  "lastName": "Gupta",
  "emailId": "howtogoinjava@gmail.com"
}

Drop me your questions related to enabling pretty printing in Gson.

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.