如何在 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"
}

更新于: 06-Jul-2020

255 次浏览

开启你的职业生涯

完成课程获得认证证书

开始学习
广告
© . All rights reserved.