该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 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"
}