คำอธิบายประกอบ @JSON ถูกใช้โดยคลาส JSONSerializer เพื่อระบุว่าจะ include หรือ exclude ฟิลด์ใดในกระบวนการ serialization เราสามารถใช้เมธอด serialize() ของ JSONSerializer เพื่อทำ shallow serialization ของ target instance
Syntax
@Retention(value=RUNTIME)
@Target(value={FIELD, TYPE, METHOD})
public @interface JSON
ตัวอย่างการใช้งาน
import flexjson.JSONSerializer;
import flexjson.JSON;
public class JSONAnnotationTest {
public static void main(String[] args) {
JSONSerializer serializer = new JSONSerializer().prettyPrint(true);
Employee emp = new Employee("Raja", "Ramesh", 30, "Hyderabad");
String jsonStr = serializer.serialize(emp);
System.out.println(jsonStr);
}
}
// Employee class
class Employee {
private String firstName, lastName, address;
private int age;
public Employee(String firstName, String lastName, int age, String address) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.address = address;
}
public String getFirstName() { return firstName; }
@JSON(include=false)
public String getLastName() { return lastName; }
public int getAge() { return age; }
@JSON(include=false)
public String getAddress() { return address; }
}
ผลลัพธ์ (Output)
{
"age": 30,
"class": "Employee",
"firstName": "Raja"
}
คำอธิบาย
ในตัวอย่าง ฟิลด์ lastName และ address ถูก annotate ด้วย @JSON(include=false) ทำให้ถูกตัดออกจาก JSON output เหลือเพียง firstName และ age (รวมถึง class metadata จากการตั้งค่า prettyPrint)
ตัวเลือกของ @JSON
include- true/false ระบุว่าจะรวมฟิลด์นี้หรือไม่name- เปลี่ยนชื่อฟิลด์ใน JSON outputformat- รูปแบบวันที่/เวลา (สำหรับ Date types)
สรุป
@JSON annotation ใน Flexjson ให้การควบคุมการ serialize ระดับฟิลด์ได้อย่างง่ายดาย เหมาะสำหรับกรณีที่ต้องการ exclude ฟิลด์บางส่วนหรือเปลี่ยนชื่อฟิลด์ใน JSON output โดยไม่ต้องสร้าง DTO แยกต่างหาก