Flexjson là thư viện Java nhẹ để serialize và de-serialize java beans, maps, arrays, và collections trong định dạng JSON. JSONSerializer là lớp chính để serialize đối tượng Java sang JSON, mặc định thực hiện shallow serialization. Có thể pretty-print JSON dùng phương thức prettyPrint(boolean prettyPrint) của JSONSerializer.
Cú pháp
public JSONSerializer prettyPrint(boolean prettyPrint)
Ví dụ minh họa
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);
}
}
// Lớp Employee
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; }
}
Kết quả đầu ra
{
"class": "Employee",
"designation": "Python Developer",
"id": "105",
"location": "Pune",
"name": "Vamsi",
"technology": "Python"
}
Lưu ý: Flexjson thêm trường "class" mặc định. Để bỏ qua, dùng serializer.exclude("class") hoặc config transformer.