@JsonIgnoreProperties
是 Jackson 庫中的一個重要注解,用于在 JSON 序列化(對象轉 JSON)和反序列化(JSON 轉對象)過程中??控制屬性的可見性??。它提供了更高級別的屬性忽略能力,特別適合處理復雜場景。
一、核心功能解析
1. 忽略特定屬性
@JsonIgnoreProperties({"password", "ssn"})
public class User {private String username;private String password; // 序列化和反序列化時被忽略private String ssn; // 序列化和反序列化時被忽略
}
2. 忽略未知屬性
@JsonIgnoreProperties(ignoreUnknown = true)
public class ApiResponse {private int status;// JSON 中包含的其他未知屬性將被忽略
}
3. 允許屬性(與 @JsonIgnore
結合)
@JsonIgnoreProperties(allowGetters = true, allowSetters = true)
public class Product {@JsonIgnoreprivate String internalCode; // 可序列化但不可反序列化
}
二、主要應用場景
1. 敏感數據隱藏
@JsonIgnoreProperties({"creditCardNumber", "cvv"})
public class Order {private String orderId;private double amount;private String creditCardNumber; // 不會出現在JSON中private String cvv; // 不會出現在JSON中
}
2. API 版本兼容
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserV2 {private String id;private String name;// 舊版本API返回的額外字段將被忽略
}
3. 循環引用處理
@JsonIgnoreProperties("manager")
public class Employee {private String name;private Employee manager; // 避免序列化時無限遞歸
}
4. 部分更新操作
@JsonIgnoreProperties(ignoreUnknown = true, value = {"id", "createdAt"})
public class UpdateUserRequest {private String id; // 不允許更新private String username; // 可更新private String email; // 可更新private Date createdAt; // 不允許更新
}
三、注解參數詳解
參數 | 類型 | 默認值 | 描述 |
---|---|---|---|
|
|
| 要忽略的屬性列表 |
|
|
| 是否忽略未知屬性 |
|
|
| 是否允許序列化(getter) |
|
|
| 是否允許反序列化(setter) |
|
|
| 是否允許反序列化(setter) |
|
|
| 屬性名前綴匹配 |
|
|
|
|
|
|
| Jackson 2.13+ 新增,簡化配置 |
四、與其他注解對比
注解 | 作用范圍 | 主要功能 | 優勢 |
---|---|---|---|
??@JsonIgnoreProperties?? | 類級別 | 批量忽略屬性 | 集中管理多個屬性 |
??@JsonIgnore?? | 字段/方法級別 | 忽略單個屬性 | 精確控制單個屬性 |
??@JsonProperty(access)?? | 字段/方法級別 | 細粒度控制 | 可指定 READ_ONLY/WRITE_ONLY |
??@JsonView?? | 字段/方法級別 | 視圖控制 | 不同場景展示不同屬性 |
五、完整使用示例
1. 安全數據傳輸
@JsonIgnoreProperties(value = {"password", "salt"}, ignoreUnknown = true)
public class UserDTO {private Long id;private String username;private String password; // 不序列化private String salt; // 不序列化// 允許獲取密碼(僅內部使用)@JsonIgnoreProperties(allowGetters = true)public String getPassword() {return password;}
}
2. API 響應包裝
@JsonIgnoreProperties(ignoreUnknown = true)
public class ApiResponse<T> {private int code;private String message;private T data;// 忽略客戶端不需要的字段@JsonIgnoreprivate String internalTraceId;
}
3. 嵌套對象處理
@JsonIgnoreProperties("employees")
public class Department {private String name;private List<Employee> employees; // 避免序列化時無限遞歸
}public class Employee {private String name;@JsonIgnoreProperties("department")private Department department; // 允許序列化部門但不包含員工列表
}
六、最佳實踐指南
1. 安全建議
// 始終忽略敏感字段
@JsonIgnoreProperties({"password", "apiKey", "secretToken"})
public class UserProfile {// ...
}
2. 版本兼容策略
// 新舊API兼容方案
@JsonIgnoreProperties(ignoreUnknown = true, value = {"legacyField"})
public class ModernEntity {private String newField;@JsonIgnore // 顯式忽略private String legacyField;
}
3. 與 Lombok 集成
@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class Product {private Long id;private String name;@JsonIgnoreprivate BigDecimal costPrice; // 成本價不暴露
}
4. 動態控制(Jackson 2.13+)
@JsonIgnoreProperties(ignore = {"createdBy", "updatedBy"})
public class AuditEntity {private String createdBy;private String updatedBy;private Date createdAt;private Date updatedAt;
}
七、常見問題解決方案
1. 忽略所有 setter 操作
@JsonIgnoreProperties(allowSetters = false)
public class SecureConfig {private String masterKey; // 可序列化但不可反序列化
}
2. 處理布爾屬性沖突
@JsonIgnoreProperties("active")
public class Account {@JsonProperty("isActive") // 使用不同名稱private boolean active;
}
3. 忽略帶前綴的屬性
@JsonIgnoreProperties(prefix = "_")
public class SystemMetrics {private int requests;private int _internalCounter; // 被忽略
}
八、進階用法
1. 組合使用注解
@JsonIgnoreProperties(ignoreUnknown = true)
public class Order {private String id;@JsonIgnoreProperties({"creditCard", "cvv"})private PaymentInfo payment; // 嵌套忽略
}
2. 元注解自定義
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@JsonIgnoreProperties({"createdAt", "updatedAt"})
public @interface AuditIgnore {}@AuditIgnore
public class User {private String name;private Date createdAt; // 自動忽略
}
3. 自定義邏輯(Jackson 2.12+)
@JsonIgnoreProperties(value = "secret", ignore = falsecondition = JsonIgnoreProperties.Condition.CUSTOM,valueFilter = SensitiveDataFilter.class
)
public class SecureDocument {private String content;private String secret;
}public class SensitiveDataFilter implements Predicate<Object> {@Overridepublic boolean test(Object value) {return !SecurityContext.isAdmin(); // 管理員可見}
}
九、與其他庫集成
1. Spring Boot 配置
@Configuration
public class JacksonConfig {@Beanpublic Jackson2ObjectMapperBuilderCustomizer jacksonCustomizer() {return builder -> builder.failOnUnknownProperties(false) // 全局忽略未知屬性.mixIn(User.class, UserMixin.class);}@JsonIgnoreProperties({"password", "salt"})public abstract class UserMixin {}
}
2. JPA 實體序列化
@Entity
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Customer {@Idprivate Long id;@OneToMany(mappedBy = "customer")@JsonIgnoreProperties("customer") // 避免循環引用private List<Order> orders;
}
十、總結
1. 核心價值
??安全性??:隱藏敏感數據
??兼容性??:處理不同版本API
??健壯性??:避免未知屬性導致的錯誤
??性能??:減少傳輸數據量
2. 使用場景
API 響應數據脫敏
新舊系統接口兼容
處理對象循環引用
動態控制屬性可見性
領域模型與DTO轉換
3. 最佳實踐
??優先類級別控制??:使用
@JsonIgnoreProperties
集中管理??細粒度補充??:配合
@JsonIgnore
處理特殊屬性??開放原則??:默認
ignoreUnknown = true
提高兼容性??安全第一??:始終忽略敏感字段
??版本策略??:使用注解實現平滑升級
@JsonIgnoreProperties
是 Jackson 庫中處理 JSON 屬性可見性的瑞士軍刀,特別在構建健壯的 API 系統和處理復雜對象關系時,能顯著提高代碼的穩定性和安全性。