Flexjson เป็น Java Library Lightweight สำหรับ Serialize และ De-serialize Java Beans, Maps, Arrays, Collections เป็น JSON Format คลาส JSONSerializer เป็น Main Class สำหรับ Serialization ทำ Shallow Serialization โดย Default สามารถ Pretty-print JSON ได้ด้วยเมธอด prettyPrint(boolean prettyPrint) ของ JSONSerializer
Syntax
public JSONSerializer prettyPrint(boolean prettyPrint)
ตัวอย่าง: Pretty Print 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) {
this.name = name;
this.id = id;
this.designation = designation;
this.technology = technology;
this.location = location;
}
// getters...
}
ผลลัพธ์
{
"class": "Employee",
"designation": "Python Developer",
"id": "105",
"location": "Pune",
"name": "Vamsi",
"technology": "Python"
}
หมายเหตุ: Flexjson เพิ่ม Field "class" อัตโนมัติ ใช้ .prettyPrint(true) ก่อน .serialize() เพื่อ Format Output ให้อ่านง่าย