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

如何用Jackson解析含嵌套数组的JSON?是否需自定义反序列化?

解析JSON中的二维数组字段,无需自定义反序列化器

完全可以通过完善现有的TestDto类实现解析,不需要自定义JsonDeserializer,Jackson原生支持这种二维数组的映射,以下是两种实用方案:

方案一:直接映射为二维集合类型

如果不需要严格的类型校验,只是想快速获取result中的数据,可以直接在TestDto中添加List<List<Object>>类型的字段,Jackson会自动完成JSON数组到集合的映射:

@JsonIgnoreProperties(ignoreUnknown = true)
public class TestDto {
    @JsonProperty("status")
    private Integer status;
    
    @JsonProperty("result")
    private List<List<Object>> result;

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public List<List<Object>> getResult() {
        return result;
    }

    public void setResult(List<List<Object>> result) {
        this.result = result;
    }
}

方案二:自定义内部元素类,实现类型安全映射

如果需要避免后续强转操作出错,追求类型安全,可以针对result中的每个子数组定义实体类,通过@JsonCreator和索引式@JsonProperty绑定数组元素的位置:

1. 定义子数组对应的实体类

public class ResultItem {
    private Integer id;
    private String foo;
    private String bar;
    private Integer value;

    @JsonCreator
    public ResultItem(
            @JsonProperty(0) Integer id,
            @JsonProperty(1) String foo,
            @JsonProperty(2) String bar,
            @JsonProperty(3) Integer value) {
        this.id = id;
        this.foo = foo;
        this.bar = bar;
        this.value = value;
    }

    // 省略getter、setter方法
}

2. 修改TestDto类

@JsonIgnoreProperties(ignoreUnknown = true)
public class TestDto {
    @JsonProperty("status")
    private Integer status;
    
    @JsonProperty("result")
    private List<ResultItem> result;

    // 省略getter、setter方法
}

两种方案都能正常解析目标JSON,根据实际需求选择即可:追求快速实现用方案一,追求类型安全用方案二。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 22:10:15