
本文介绍在 Spring Boot 项目中使用 Jackson 注解(如 @JsonIgnore)精准控制 JSON 序列化/反序列化行为,避免敏感或冗余字段(如 customer 关联对象)被意外暴露或解析。
本文介绍在 spring boot 项目中使用 jackson 注解(如 `@jsonignore`)精准控制 json 序列化/反序列化行为,避免敏感或冗余字段(如 `customer` 关联对象)被意外暴露或解析。
在基于 Spring Boot 的 RESTful 应用中,当 Visit 实体类通过 @RestController 返回给前端时,Jackson 默认会将所有非静态、非瞬态(non-transient)的公共字段或 getter 方法对应的属性序列化为 JSON。然而,像 Visit.customer 这样的关联对象,若未加约束,可能引发循环引用、数据冗余或安全风险(例如泄露用户完整信息)。此时,应主动排除该字段。
最直接、推荐的做法是在字段级别添加 @JsonIgnore 注解:
package fact.it.examcustomercheck.entities;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.Calendar;
public class Visit {
private int enterWeight;
private int exitWeight;
@JsonIgnore // ← 关键:阻止 customer 字段参与 JSON 序列化与反序列化
private Customer customer;
// 其他 getter/setter 方法保持不变...
public int getDepositedWeight() {
return this.enterWeight - this.exitWeight;
}
public int getMembershipAge() {
int year = Calendar.getInstance().get(Calendar.YEAR);
return year - this.customer.getYearOfRegistration();
}
public int getCost() {
if (getDepositedWeight() 5) {
return 0;
} else if (getDepositedWeight() <blockquote>
<p>✅ <strong>注意事项</strong>:</p>
<ul>
<li>确保导入正确包:com.fasterxml.jackson.annotation.JsonIgnore(非 javax.json 或其他 JSON 库);</li>
<li>@JsonIgnore 同时禁用该字段的序列化(响应体)和反序列化(请求体),适用于完全不需要传输的字段;</li>
<li>若仅需忽略序列化但保留反序列化(如仅读取不输出),可改用 @JsonIgnoreProperties(value = {"customer"}, allowSetters = true);</li>
<li>避免在业务逻辑强依赖 customer 的方法(如 getMembershipAge()、toString())中直接访问被忽略的字段——这本身无问题,因为注解仅影响 JSON 处理,不影响 Java 运行时对象行为;</li>
<li>如需更细粒度控制(如按序列化方向、视图或条件忽略),可结合 @JsonView、@JsonInclude 或自定义 Serializer 使用。</li>
</ul>
</blockquote><p>综上,@JsonIgnore 是解决“客户访问记录中隐藏客户详情”这一典型场景的轻量、高效且符合 Spring Boot 惯例的方案。它无需修改 DTO 层或配置全局 Jackson 行为,即可实现字段级精准脱敏,兼顾开发效率与 API 安全性。</p>











