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" }
以上是如何使用Java中的Gson庫對JSON進行漂亮列印?的詳細內容。更多資訊請關注PHP中文網其他相關文章!