如何使用 Java 中的 Gson 庫對 JSON 進行漂亮列印?


一個Gson 是 Google 建立的針對 java 的 JSON 庫。透過使用 Gson,我們可以生成 JSON 並將 JSON 轉換為 java 物件。預設情況下,Gson 可以按緊湊格式列印 JSON。若要啟用Gson 漂亮列印,我們必須使用GsonBuilder 類的setPrettyPrinting()方法配置 Gson 例項,並且此方法將 Gson 配置為輸出適合一頁且用於漂亮列印的 JSON。

語法

public GsonBuilder setPrettyPrinting()

示例

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

輸出

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

更新日期: 04-Jul-2020

4 千次以上瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始
廣告