Gson – Pretty Print JSON

By default, Gson prints the JSON in compact format. It means there will not be any whitespace in between field names and its 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.

By Default, Gson format the output JSON with default line length of 80 character, 2 character indentation, and 4 character right margin.

Gson gson = new GsonBuilder()

String jsonOutput = gson.toJson(someObject);

2. JSON pretty print example

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;

    //Getters and setters

public class Main 
	public static void main(String[] args) 
		Employee employeeObj = new Employee(1, "Lokesh", "Gupta", "");
		Gson gson = new GsonBuilder()

Program output.

  "id": 1,
  "firstName": "Lokesh",
  "lastName": "Gupta",
  "emailId": ""

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

Happy Learning !!


Gson User Guide

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

1 thought on “Gson – Pretty Print JSON”

  1. In my case I am executing an API in browser. The Object to convert is an ArrayList with more than 30 size and 20 fields. When I try to see the output in browser it looks weird.


Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.