Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีแปลง Bean เป็น JSON Object โดย Exclude Properties ด้วย JsonConfig (Java)

คลาส JsonConfig เป็น utility class ช่วยตั้งค่ากระบวนการ serialization เราสามารถแปลง bean เป็น JSON object โดย exclude บาง properties ได้ด้วยเมธอด setExcludes() ของ JsonConfig และส่ง JsonConfig instance นี้เป็น argument ของเมธอด static fromObject() ของ JSONObject

Syntax

public void setExcludes(String[] excludes)

ตัวอย่างการใช้งาน

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

public class BeanToJsonExcludeTest {
    public static void main(String[] args) {
        Student student = new Student("Raja", "Ramesh", 35, "Madhapur");
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setExcludes(new String[]{"age", "address"});
        JSONObject obj = JSONObject.fromObject(student, jsonConfig);
        System.out.println(obj.toString(3)); // pretty print JSON
    }
    
    public static class Student {
        private String firstName, lastName, address;
        private int age;
        
        public Student(String firstName, String lastName, int age, String address) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.age = age;
            this.address = address;
        }
        
        // getters...
        public String getFirstName() { return firstName; }
        public String getLastName() { return lastName; }
        public int getAge() { return age; }
        public String getAddress() { return address; }
    }
}

ผลลัพธ์ (Output)

{
  "firstName": "Raja",
  "lastName": "Ramesh"
}

คำอธิบาย

ในตัวอย่าง ฟิลด์ age และ address ถูก exclude ออกจาก JSON output ผลลัพธ์เหลือเพียง firstName และ lastName เท่านั้น

การใช้งานร่วมกับ setIncludes()

JsonConfig ยังมี setIncludes(String[]) สำหรับระบุว่าให้ include เฉพาะฟิลด์ไหน (whitelist approach):

jsonConfig.setIncludes(new String[]{"firstName", "lastName"}); // เก็บแค่ 2 ฟิลด์นี้

กรณีการใช้งาน (Use Cases)

  • Security - ไม่ส่งข้อมูล nhạy cảm เช่น password, SSN, salary
  • Performance - ลดขนาด payload โดยตัดฟิลด์ที่ไม่จำเป็น
  • API Versioning - แสดงฟิลด์ต่างกันตาม version
  • Conditional Serialization - exclude ตามเงื่อนไข runtime

สรุป

JsonConfig.setExcludes() ให้วิธีง่ายและชัดเจนในการ exclude properties โดยชื่อ เหมาะสำหรับกรณีที่ทราบล่วงหน้าว่าฟิลด์ไหนไม่ควร serialize ไปยัง client