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

วิธี Exclude Field จาก JSON ด้วย @Expose Annotation ใน Java (Gson)

Annotation @Expose ของ Gson ใช้ทำเครื่องหมาย Field ให้ Expose (รวม) หรือไม่ (Exclude) สำหรับ Serialization หรือ Deserialization @Expose รับ Parameter 2 ตัว เป็น Boolean (true/false) ต้องสร้าง Gson Instance ผ่าน GsonBuilder เรียก excludeFieldsWithoutExposeAnnotation() เพื่อให้ Gson ตอบสนองต่อ @Expose

Syntax

public GsonBuilder excludeFieldsWithoutExposeAnnotation()

ตัวอย่าง: ใช้ @Expose ควบคุม Field

import com.google.gson.*;
import com.google.gson.annotations.*;

public class JsonExcludeAnnotationTest {
    public static void main(String[] args) {
        Employee emp = new Employee("Raja", 28, 40000.00);
        
        // โดยไม่มี excludeFieldsWithoutExposeAnnotation() - Serialize ทุก Field
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String jsonStr = gson.toJson(emp);
        System.out.println(jsonStr);
        
        // มี excludeFieldsWithoutExposeAnnotation() - Serialize เฉพาะ Field ที่มี @Expose
        gson = new GsonBuilder()
            .setPrettyPrinting()
            .excludeFieldsWithoutExposeAnnotation()
            .create();
        jsonStr = gson.toJson(emp);
        System.out.println(jsonStr);
    }
}

// Employee class
class Employee {
    @Expose(serialize = true, deserialize = true)
    public String name;
    
    @Expose(serialize = true, deserialize = true)
    public int age;
    
    @Expose(serialize = false, deserialize = false)
    public double salary;  // จะถูก Exclude
    
    public Employee(String name, int age, double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }
}

ผลลัพธ์

// ก่อนใช้ excludeFieldsWithoutExposeAnnotation()
{ "name": "Raja", "age": 28, "salary": 40000.0 }

// หลังใช้ excludeFieldsWithoutExposeAnnotation()
{ "name": "Raja", "age": 28 }

จุดสำคัญ: ต้องเรียก excludeFieldsWithoutExposeAnnotation() บน GsonBuilder ถึงจะมีผล Force ให้ Exclude Field ที่ไม่มี @Expose