登录
首页 >  文章 >  java教程

Jackson生成JSON的完整教程详解

时间:2026-03-07 14:39:39 107浏览 收藏

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

Java 中使用 Jackson 精确生成 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学习网公众号吧!

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>