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

Bỏ qua field khi serialize JSON với @JsonIgnore (Jackson)

Annotation @JsonIgnore loại bỏ field khỏi cả serialization và deserialization. Có thể đặt trên field, getter, hoặc setter.

Ví dụ: Ẩn danh sách công nghệ nội bộ


import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
import java.io.IOException;
import java.util.*;

public class JsonIgnoreDemo {
    public static void main(String[] args) throws IOException {
        Employee emp = new Employee();
        emp.setEmpId(100);
        emp.setFirstName("Minh");
        emp.setLastName("Nguyễn");
        emp.getTechnologies().add("Java");
        emp.getTechnologies().add("Kubernetes");
        emp.getTechnologies().add("Internal-Framework"); // không muốn public
        
        ObjectMapper mapper = new ObjectMapper();
        mapper.writerWithDefaultPrettyPrinter().writeValue(System.out, emp);
    }
}

class Employee {
    private int empId;
    private String firstName, lastName;
    
    @JsonIgnore // Ẩn field này hoàn toàn
    private List<String> technologies = new ArrayList<>();
    
    // Getters/Setters
    public int getEmpId() { return empId; }
    public void setEmpId(int id) { empId = id; }
    public String getFirstName() { return firstName; }
    public void setFirstName(String fn) { firstName = fn; }
    public String getLastName() { return lastName; }
    public void setLastName(String ln) { lastName = ln; }
    
    public List<String> getTechnologies() { return technologies; }
    public void setTechnologies(List<String> techs) { technologies = techs; }
}

Kết quả


{
  "empId" : 100,
  "firstName" : "Minh",
  "lastName" : "Nguyễn"
}

Các vị trí đặt @JsonIgnore

Vị tríTác động
Trên fieldBỏ qua cả read & write
Trên getterChỉ bỏ qua serialize (write)
Trên setterChỉ bỏ qua deserialize (read)

Annotation liên quan

  • @JsonIgnoreProperties({"field1", "field2"}) trên class – bỏ qua nhiều field
  • @JsonIgnoreType – bỏ qua toàn bộ kiểu dữ liệu
  • @JsonProperty(access = Access.WRITE_ONLY) – chỉ deserialize, không serialize
  • @JsonProperty(access = Access.READ_ONLY) – chỉ serialize, không deserialize