You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Jackson ObjectMapper映射嵌套层级中含无名称对象数组的JSON

解决方案

核心问题是JSON中entry字段为数组类型,当前代码用单个SectionEntry类型接收导致类型不匹配,按以下步骤调整即可:

  1. 修改ComponentSection类的entry字段类型
public class ComponentSection {

    @JsonProperty("ID")
    private String id;
    @JsonProperty("code")
    private Code code;
    @JsonProperty("entry")
    // 改为List类型接收数组结构
    private List<SectionEntry> entry;

    // 补充对应getter、setter方法
}
  1. 补全层级关联的实体类定义
    逐层定义SectionEntry、Act、EntryRelationship类,匹配JSON结构中的属性:
// 对应entry数组内的对象结构
public class SectionEntry {
    @JsonProperty("act")
    private Act act;
    @JsonProperty("id")
    private String id;

    // 补充getter、setter方法
}

// 对应act字段的对象结构
public class Act {
    @JsonProperty("classCode")
    private String classCode;
    @JsonProperty("entryRelationship")
    private EntryRelationship entryRelationship;

    // 补充getter、setter方法
}

// 对应entryRelationship字段的对象结构
public class EntryRelationship {
    @JsonProperty("name")
    private String name;

    // 补充getter、setter方法
}
  1. 可选兼容配置
    如果业务场景中存在entry字段有时返回单个对象、有时返回数组的情况,可添加以下注解兼容两种格式,无需额外编写自定义反序列化逻辑:
@JsonProperty("entry")
@JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
private List<SectionEntry> entry;

外层更高层级的嵌套结构按同样逻辑,逐层定义实体类添加@JsonProperty注解映射即可,原有ObjectMapper的使用逻辑不需要调整。

内容的提问来源于stack exchange,提问作者Mauricio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 13:45:02