如何在 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"
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP