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

วิธีแปลง Bean เป็น JSON Object ด้วย Exclude Filter ใน Java (JSON-lib)

คลาส JsonConfig ใช้สำหรับตั้งค่ากระบวนการ serialization เราสามารถใช้เมธอด setJsonPropertyFilter() ของ JsonConfig เพื่อตั้งค่า property filter ระหว่าง serialize เป็น JSON เราต้อง implement custom PropertyFilter class โดย override เมธอด apply() ของ PropertyFilter interface คืนค่า true ถ้าต้องการ filter out (ตัดทิ้ง) property นั้น false ถ้าเก็บไว้

Syntax

public void setJsonPropertyFilter(PropertyFilter jsonPropertyFilter)

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

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

public class ConvertBeanToJsonExcludeFilterTest {
    public static void main(String[] args) {
        Student student = new Student("Sai", "Chaitanya", 20, "Hyderabad");
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setJsonPropertyFilter(new CustomPropertyFilter());
        JSONObject jsonObj = JSONObject.fromObject(student, jsonConfig);
        System.out.println(jsonObj.toString(3)); // pretty print JSON
    }
    
    public static class Student {
        private String firstName, lastName, address;
        public 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; }
    }
}

// CustomPropertyFilter class
class CustomPropertyFilter implements PropertyFilter {
    @Override
    public boolean apply(Object source, String name, Object value) {
        if (Number.class.isAssignableFrom(value.getClass()) ||
            String.class.isAssignableFrom(value.getClass())) {
            return false; // เก็บไว้ (ไม่ filter)
        }
        return true; // filter out
    }
}

ผลลัพธ์ (Output)

{
  "firstName": "Sai",
  "lastName": "Chaitanya",
  "address": "Hyderabad",
  "age": 20
}

คำอธิบาย

ในตัวอย่าง CustomPropertyFilter จะ filter out (คืนค่า true) สำหรับ property ที่ไม่ใช่ Number หรือ String แต่ใน output ดูเหมือนจะเก็บทุกฟิลด์ไว้ (อาจมี inconsistency ในตัวอย่างต้นฉบับ) ตรรกะที่ถูกต้องควรเป็น:

  • คืนค่า false = เก็บ property ไว้ (include)
  • คืนค่า true = ตัด property ออก (exclude)

การใช้งานแบบง่ายกว่า: setExcludes()

JSON-lib ยังมีเมธอด setExcludes(String[]) สำหรับ exclude ฟิลด์โดยชื่อโดยตรง (ดูบทความถัดไป)

สรุป

JsonConfig และ PropertyFilter ให้การควบคุม serialization แบบ programmatic และ dynamic เหมาะสำหรับกรณีที่ต้องการ filter ตามเงื่อนไขซับซ้อน (เช่น ตาม type, ค่า, หรือ context)