หากมีฟิลด์ใน Java object ที่ไม่ต้องการให้ serialize ใช้ annotation @JsonIgnore ของไลบรารี Jackson สามารถวางที่ระดับ field เพื่อข้ามฟิลด์นั้นระหว่าง serialization และ deserialization
ไวยากรณ์
public @interface JsonIgnore
ตัวอย่างโค้ด
import java.io.*;
import java.util.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.annotation.*;
public class JsonIgnoreAnnotationTest {
public static void main(String[] args) throws Exception {
Employee emp = new Employee();
emp.setFirstName("Raja");
emp.setLastName("Ramesh");
emp.setEmpId(120);
emp.getTechnologies().add("Java");
emp.getTechnologies().add("Scala");
emp.getTechnologies().add("Python");
ObjectMapper mapper = new ObjectMapper();
mapper.writerWithDefaultPrettyPrinter().writeValue(System.out, emp);
}
}
// Employee class
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"firstName", "lastName", "technologies", "empId"})
class Employee {
@JsonProperty("EMPLOYEE_ID")
private int empId;
@JsonProperty("EMPLOYEE_FIRST_NAME")
private String firstName;
@JsonProperty("EMPLOYEE_LAST_NAME")
private String lastName;
@JsonIgnore // <-- ไม่ serialize ฟิลด์นี้
private List<String> technologies = new ArrayList<>();
// Getters & Setters...
public int getEmpId() { return empId; }
public void setEmpId(int empId) { this.empId = empId; }
public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }
public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }
public List<String> getTechnologies() { return technologies; }
public void setTechnologies(List<String> technologies) { this.technologies = technologies; }
}
ผลลัพธ์
{
"EMPLOYEE_FIRST_NAME" : "Raja",
"EMPLOYEE_LAST_NAME" : "Ramesh",
"EMPLOYEE_ID" : 120
}
สังเกตว่า technologies ไม่อยู่ใน JSON output
การใช้งาน @JsonIgnore ที่ต่างกัน
| ตำแหน่ง | ผลลัพธ์ |
|---|---|
| บน Field | ข้ามทั้ง serialize และ deserialize |
| บน Getter | ข้าม serialize เท่านั้น (deserialize ได้) |
| บน Setter | ข้าม deserialize เท่านั้น (serialize ได้) |
| บน Constructor parameter | ข้าม deserialize จาก constructor |
ตัวอย่าง: ข้ามเฉพาะ Serialize (Getter)
private String password;
@JsonIgnore
public String getPassword() { return password; } // ไม่ serialize
public void setPassword(String password) { this.password = password; } // deserialize ได้
ทางเลือกอื่น
@JsonProperty(access = Access.WRITE_ONLY)- deserialize ได้ แต่ไม่ serialize@JsonProperty(access = Access.READ_ONLY)- serialize ได้ แต่ไม่ deserialize@JsonIgnoreProperties({"field1", "field2"})บนคลาส - ระบุหลายฟิลด์พร้อมกัน