如何在 Java 中使用 flexjson 庫來美化列印 JSON?\n
Flexjson 是一個輕量級 Java 庫,用於將java bean、對映、陣列和集合以JSON 格式序列化和反序列化。JSONSerializer 是用於執行 Java 物件到 JSON 序列化的主要類,預設情況下執行淺層 序列化。我們可以使用JSONSerializer 類的prettyPrint(boolean prettyPrint)方法美化列印JSON。
語法
public JSONSerializer prettyPrint(boolean prettyPrint)
在下面的程式中,使用 flexjson 庫美化列印 JSON
示例
import flexjson.*; public class PrettyPrintJSONTest { public static void main(String[] args) { JSONSerializer serializer = new JSONSerializer().prettyPrint(true); // pretty print Employee emp = new Employee("Vamsi", "105", "Python Developer", "Python", "Pune"); String jsonStr = serializer.serialize(emp); System.out.println(jsonStr); } } // 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; } }
輸出
{ "class": "Employee", "designation": "Python Developer", "id": "105", "location": "Pune", "name": "Vamsi", "technology": "Python" }
廣告