使用 Java 中的 flexjson 库来漂亮地打印 JSON?\
javajsonobject oriented programmingprogramming
Flexjson 是一个 轻量级 Java 库,用于 序列化 和 反序列化 Java bean、map、数组和 集合 (采用 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 classclass 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" }