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

Spring中Jackson反序列化Map时costDetail为null问题排查

问题分析与解决方案

你的反序列化失败主要是模型层级不匹配和Jackson字段访问权限问题导致的,具体原因和修复步骤如下:

核心问题拆解

  1. JSON层级与模型不对应
    原JSON中cmop下的每个数字键(如1001678)对应的值是包含info节点的对象,但你的CostDeal直接映射到CostDetail,跳过了info这一层,导致Jackson无法找到匹配的字段。

  2. 私有字段访问限制
    所有模型类的字段都是private且未提供getter/setter,Jackson默认无法直接访问私有字段,因此无法完成赋值。

  3. CostDeal的Map字段无对应映射
    cmop下直接是数字键,没有名为costDetail的节点,但你的CostDeal类定义了costDetail字段,Jackson无法将JSON中的数字键值对映射到这个字段。

修复步骤

步骤1:调整模型层级,新增中间类匹配info节点

新增一个类封装info层级,让模型完全对齐JSON结构:

public class InfoWrapper {
    @JsonProperty("info")
    private Map<String, CostDetail> info;

    // 添加getter/setter
    public Map<String, CostDetail> getInfo() {
        return info;
    }

    public void setInfo(Map<String, CostDetail> info) {
        this.info = info;
    }
}

步骤2:修正CostDeal类的Map类型

让CostDeal的Map对应cmop下的数字键,值为新增的InfoWrapper:

public class CostDeal {
    private Map<String, InfoWrapper> costDetails;

    // 添加getter/setter
    public Map<String, InfoWrapper> getCostDetails() {
        return costDetails;
    }

    public void setCostDetails(Map<String, InfoWrapper> costDetails) {
        this.costDetails = costDetails;
    }
}

步骤3:完善原有类的getter/setter

给Campaign和CostDetail添加getter/setter,确保Jackson能访问字段:

public class Campaign {
    @JsonProperty("cmop")
    private CostDeal costDeal;

    public CostDeal getCostDeal() {
        return costDeal;
    }

    public void setCostDeal(CostDeal costDeal) {
        this.costDeal = costDeal;
    }
}
public class CostDetail {
    @JsonProperty("wt")
    private int weightage;

    public int getWeightage() {
        return weightage;
    }

    public void setWeightage(int weightage) {
        this.weightage = weightage;
    }
}

可选:配置Jackson直接访问私有字段

如果不想添加getter/setter,可以通过ObjectMapper配置允许访问私有字段:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

验证反序列化

使用修正后的模型和配置,即可正常将JSON反序列化为Campaign对象,costDetails Map不再为null。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 14:40:08