Computer >> Máy Tính >  >> Lập trình >> Java

Làm thế nào để in JSON đẹp bằng cách sử dụng thư viện Gson trong Java?


A Gson là một thư viện JSON cho java, được tạo bởi Google. Bằng cách sử dụng Gson, chúng tôi có thể tạo JSON và chuyển đổi JSON sang các đối tượng java. Theo mặc định, Gson có thể in JSON ở định dạng nhỏ gọn . Để bật Gson pretty print , chúng tôi phải định cấu hình phiên bản Gson bằng cách sử dụng setPrettyPrinting () phương thức của GsonBuilder và phương thức này định cấu hình Gson để xuất ra JSON phù hợp với một trang để in ấn đẹp.

Cú pháp

public GsonBuilder setPrettyPrinting()

Ví dụ

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;
   }
}

Đầu ra

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