How to pretty print JSON using the Gson library in Java?

A Gson is a JSON library for java, which is created by Google. By using Gson, we can generate JSON and convert JSON to java objects. By default, Gson can print the JSON in compact format. To enable Gson pretty print, we must configure the Gson instance using the setPrettyPrinting() method of GsonBuilder class and this method configures Gson to output JSON that fits in a page for pretty printing.


public GsonBuilder setPrettyPrinting()


import java.util.*;
public class PrettyJSONTest {
   public static void main( String[] args ) {
      Employee emp = new Employee("Raja", "115", "Content Engineer", "Java", "Hyderabad");
      Gson gson = new GsonBuilder().setPrettyPrinting().create(); // pretty print
      String prettyJson = gson.toJson(emp);
// Employee class
class Employee {
   private String name, id, designation, technology, location;
   public Employee(String name, String id, String designation, String technology, String location) {
      super(); = name; = id;
      this.designation = designation; = technology;
      this.location = location;
   public String getName() {
      return name;
   public String getId() {
      return id;
   public String getDesignation() {
      return designation;
   public String getTechnology() {
      return technology;
   public String getLocation() {
      return location;


 "name": "Raja",
 "id": "115",
 "designation": "Content Engineer",
 "technology": "Java",
 "location": "Hyderabad"