Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Loại trừ trường khỏi JSON bằng annotation @Expose trong Java

Annotation @Expose của Gson dùng để đánh dấu trường được expose (bao gồm) hay không cho serialization/deserialization. @Expose nhận 2 tham số boolean: serialize và deserialize (true/false). Để Gson phản ứng với @Expose, phải tạo instance Gson dùng GsonBuilder và gọi excludeFieldsWithoutExposeAnnotation(), cấu hình Gson loại trừ tất cả trường không có annotation Expose.

Cú pháp

public GsonBuilder excludeFieldsWithoutExposeAnnotation()

Ví dụ minh họa

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);
        
        // Không dùng @Expose filter
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String jsonStr = gson.toJson(emp);
        System.out.println(jsonStr);
        
        // Dùng @Expose filter
        gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create();
        jsonStr = gson.toJson(emp);
        System.out.println(jsonStr);
    }
}

// Lớp Employee
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;
    
    public Employee(String name, int age, double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }
}

Kết quả đầu ra

{
    "name": "Raja",
    "age": 28,
    "salary": 40000.0
}
{
    "name": "Raja",
    "age": 28
}

So sánh với transient: @Expose linh hoạt hơn - có thể kiểm soát riêng serialize vs deserialize, còn transient loại trừ cả hai. @Expose cũng hoạt động với field private (cần getter/setter).