@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 系统和处理复杂对象关系时,能显著提高代码的稳定性和安全性。