使用Jackson ObjectMapper映射嵌套层级中含无名称对象数组的JSON
解决方案
核心问题是JSON中entry字段为数组类型,当前代码用单个SectionEntry类型接收导致类型不匹配,按以下步骤调整即可:
- 修改
ComponentSection类的entry字段类型
public class ComponentSection { @JsonProperty("ID") private String id; @JsonProperty("code") private Code code; @JsonProperty("entry") // 改为List类型接收数组结构 private List<SectionEntry> entry; // 补充对应getter、setter方法 }
- 补全层级关联的实体类定义
逐层定义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方法 }
- 可选兼容配置
如果业务场景中存在entry字段有时返回单个对象、有时返回数组的情况,可添加以下注解兼容两种格式,无需额外编写自定义反序列化逻辑:
@JsonProperty("entry") @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY) private List<SectionEntry> entry;
外层更高层级的嵌套结构按同样逻辑,逐层定义实体类添加@JsonProperty注解映射即可,原有ObjectMapper的使用逻辑不需要调整。
内容的提问来源于stack exchange,提问作者Mauricio
相关产品推荐
相关产品推荐

