Jackson生成JSON的完整教程详解
时间:2026-03-07 14:39:39 107浏览 收藏
本文深入解析了如何利用 Jackson 的 `@JsonIgnore` 等注解精准控制 Java 对象序列化行为,彻底解决因默认 getter 推导机制导致的冗余字段(如 null、0 值)污染 JSON 输出的问题;通过在 getter 方法上显式标注 `@JsonIgnore` 排除非 API 所需字段,并辅以 `@JsonProperty` 明确声明关键键名,开发者能稳定生成轻量、规范、零误差的 JSON 请求体,完美契合严苛的第三方接口契约——无论你是调试失败的 API 调用,还是构建高可靠微服务,这套经过验证的实践都能让你告别 JSON 校验失败和传输膨胀的烦恼。

本文详解如何通过 Jackson 注解(如 @JsonIgnore、@JsonIgnoreProperties)精准控制 DTO 序列化行为,排除冗余字段,确保输出 JSON 严格符合 API 规范要求。
本文详解如何通过 Jackson 注解(如 `@JsonIgnore`、`@JsonIgnoreProperties`)精准控制 DTO 序列化行为,排除冗余字段,确保输出 JSON 严格符合 API 规范要求。
在 Java 后端开发中,构建符合第三方 API 接口契约的 JSON 请求体是常见需求。若 DTO 类中存在未参与序列化的业务字段(如 aid、alabel、intvalue),而 Jackson 默认会将所有 getter 方法对应的属性(包括未标注 @JsonProperty 的字段)尝试写入 JSON,就会导致输出包含大量 null 或默认值(如 0)的冗余字段——这不仅增大传输体积,更可能被严格校验的 API 拒绝。
核心问题在于:Jackson 默认序列化策略是“按 getter 推导字段”,而非“仅序列化显式标注的字段”。因此,解决思路不是“过滤输出”,而是主动声明哪些字段不应出现在 JSON 中。
✅ 正确做法:使用 @JsonIgnore 精确排除非 JSON 字段
最直接、可靠的方式是对不需要序列化的字段或其 getter 方法添加 @JsonIgnore 注解。相比 @JsonIgnoreProperties(ignoreUnknown = true)(该注解仅用于反序列化时忽略未知字段,对序列化无效),@JsonIgnore 才是控制序列化输出的关键。
以 AttDTO 类为例,只需为 aid、alabel 和 intvalue 对应的 getter 方法添加 @JsonIgnore:
public class AttDTO {
@JsonProperty("name")
private String aname;
@JsonProperty("type")
private String atype;
@JsonProperty("value")
private String avalue;
private String aid;
private String alabel;
private int intvalue;
// ... 构造方法与其它 getter/setter ...
@JsonIgnore // ← 关键:阻止 aid 被序列化
public String getAid() {
return aid;
}
@JsonIgnore // ← 关键:阻止 alabel 被序列化
public String getAlabel() {
return alabel;
}
@JsonIgnore // ← 关键:阻止 intvalue 被序列化
public int getIntvalue() {
return intvalue;
}
}⚠️ 注意:@JsonIgnore 必须加在 getter 方法上(而非字段),因为 Jackson 默认使用 accessor(getter/setter)机制进行序列化。若加在字段上且未启用 MapperFeature.USE_GETTERS_AS_SETTERS,可能无效。
✅ 补充优化:确保 BaseDTO 中 attributes 字段命名与 JSON 一致
当前 BaseDTO 中已正确使用 @JsonProperty 声明字段名,但需注意两点:
- ArrayList
attributes 字段本身未加 @JsonProperty("attributes"),依赖默认命名规则(字段名即 JSON key)。虽当前有效,但显式声明更健壮; - attributes 的 getter/setter 应保持标准命名(getAttributes()/setAttributes()),避免 Jackson 因命名不规范而忽略。
推荐完善 BaseDTO 的字段声明:
@JsonProperty("attributes")
private ArrayList<AttDTO> attributes;✅ 完整可运行示例
// AttDTO.java
public class AttDTO {
@JsonProperty("name") private String aname;
@JsonProperty("type") private String atype;
@JsonProperty("value") private String avalue;
private String aid;
private String alabel;
private int intvalue;
public AttDTO(String aname, String atype, String avalue) {
this.aname = aname;
this.atype = atype;
this.avalue = avalue;
}
// 显式标注 JSON 字段
public String getAname() { return aname; }
public void setAname(String aname) { this.aname = aname; }
public String getAtype() { return atype; }
public void setAtype(String atype) { this.atype = atype; }
public String getAvalue() { return avalue; }
public void setAvalue(String avalue) { this.avalue = avalue; }
// 明确忽略非 JSON 字段
@JsonIgnore public String getAid() { return aid; }
@JsonIgnore public void setAid(String aid) { this.aid = aid; }
@JsonIgnore public String getAlabel() { return alabel; }
@JsonIgnore public void setAlabel(String alabel) { this.alabel = alabel; }
@JsonIgnore public int getIntvalue() { return intvalue; }
@JsonIgnore public void setIntvalue(int intvalue) { this.intvalue = intvalue; }
}
// BaseDTO.java
public class BaseDTO {
@JsonProperty("id") private String id;
@JsonProperty("type") private String type;
@JsonProperty("attributes") private ArrayList<AttDTO> attributes;
public BaseDTO(String id, String type, ArrayList<AttDTO> attributes) {
this.id = id;
this.type = type;
this.attributes = attributes;
}
// getter/setter 省略(需补全标准实现)
}
// 测试主类
public class EntityCreator {
public static void main(String[] args) throws Exception {
ArrayList<AttDTO> attrs = new ArrayList<>();
attrs.add(new AttDTO("publisherId", "Text", "APM"));
BaseDTO obj = new BaseDTO("APMManufacturingTasksDefReq1",
"APMManufacturingTasksDefReq",
attrs);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(obj);
System.out.println(json);
// 输出:{"id":"APMManufacturingTasksDefReq1","type":"APMManufacturingTasksDefReq","attributes":[{"name":"publisherId","type":"Text","value":"APM"}]}
}
}? 总结
- ✅ 优先使用 @JsonIgnore 标注不需要序列化的 getter 方法,这是最精准、最易维护的方案;
- ❌ 避免误用 @JsonIgnoreProperties(ignoreUnknown = true) 控制序列化输出(它仅作用于反序列化);
- ✅ 显式声明 @JsonProperty 可提升代码可读性与契约稳定性;
- ✅ 使用 Lombok 的 @Getter / @Setter 时,需配合 @JsonIgnore 在字段级或通过 @Accessors + @JsonIgnore 组合控制,但手动 getter 更可控;
- ? 始终通过单元测试验证最终 JSON 结构,确保与 API 文档完全一致。
遵循以上实践,即可稳定、可预测地生成精简、合规的 JSON 请求体。
理论要掌握,实操不能落!以上关于《Jackson生成JSON的完整教程详解》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
324 收藏
-
279 收藏
-
481 收藏
-
213 收藏
-
406 收藏
-
386 收藏
-
140 收藏
-
346 收藏
-
462 收藏
-
242 收藏
-
270 收藏
-
493 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习