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

How to pretty print JSON using Gson library in Java?

PHPz
Release: 2023-09-13 21:05:11
forward
1397 people have browsed it

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()
Copy after login

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;
   }
}
Copy after login

Output

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

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template