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

Điều khiển serialization bằng @JSON annotation dùng Flexjson (Java)

Annotation @JSON của thư viện Flexjson dùng để include/exclude field khi serialize. Class JSONSerializer thực hiện serialization.

Cú pháp

@Retention(RUNTIME)
@Target({FIELD, TYPE, METHOD})
public @interface JSON {
    boolean include() default true;
}

Ví dụ minh họa

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);
    }
}

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) // Loại bỏ lastName
    public String getLastName() { return lastName; }
    
    public int getAge() { return age; }
    
    @JSON(include = false) // Loại bỏ address
    public String getAddress() { return address; }
}

Output

{
  "age": 30,
  "class": "Employee",
  "firstName": "Raja"
}

Các tính năng khác của Flexjson

  • @JSON(include=false) trên class: exclude toàn bộ class.
  • serializer.exclude("fieldName") / include("fieldName") cấu hình programmatic.
  • serializer.transform(new DateTransformer(), Date.class) custom format cho type.
  • Deep serialization control với Serializer interface.

Lưu ý

Flexjson là thư viện cũ (chưa cập nhật nhiều năm). Dự án mới nên dùng Jackson hoặc Gson - phổ biến, hiệu suất tốt, community lớn. Jackson dùng @JsonIgnore, @JsonProperty, @JsonInclude để đạt tương tự.