Home >Java >javaTutorial >How to pretty print JSON using Gson library in Java?

How to pretty print JSON using Gson library in Java?

PHPz
PHPzforward
2023-09-13 21:05:111400browse

How to pretty print JSON using Gson library in Java?

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

Syntax

public GsonBuilder setPrettyPrinting()

Example

import java.util.*;
import com.google.gson.*;
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);
      System.out.println(prettyJson);
   }
}
// Employee class
class Employee {
   private String name, id, designation, technology, location;
   public Employee(String name, String id, String designation, String technology, String location) {
      super();
      this.name = name;
      this.id = id;
      this.designation = designation;
      this.technology = 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;
   }
}

Output

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

The above is the detailed content of How to pretty print JSON using Gson library in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete