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

Jackson中@JsonProperty的defaultValue对基本类型不生效怎么办?

问题:Jackson解析int类型字段时@JsonProperty的defaultValue不生效

我有如下Jackson实体类:

public class InspectArrayFormulaArgs {

    private final int expectedColumns;

    @JsonCreator
    public InspectArrayFormulaArgs(@JsonProperty(value = "expectedColumns", defaultValue = "-1") int expectedColumns) {
        this.expectedColumns = expectedColumns;
    }

}

期望的解析行为:

  • JSON中存在expectedColumns字段时,直接使用该字段的值
  • JSON中不存在该字段时,使用@JsonProperty声明的defaultValue="-1"

但实际解析后,expectedColumns的值始终为0。推测原因是JDK会将int类型默认初始化为0,Jackson在JSON无该字段时未触发defaultValue的赋值逻辑。

尝试过将构造器参数改为Integer类型,但会触发NullPointerException——Jackson未赋值默认值-1,而是传入null,拆箱到int类型字段时出错。

备注:

  1. 曾用@JsonInclude(JsonInclude.Include.NON_DEFAULT)注解该类,无效果
  2. 可将字段改为Integer类型,但Jackson会留为null,希望避免手动写value != null ? value : -1这类判断,确认是否为Jackson用法有误。

解决方案

方法1:使用Jackson 2.9+的@JsonSetter指定默认值(推荐)

将构造器参数改为Integer类型,配合@JsonSetter配置null值处理和默认值,Jackson会自动将null替换为指定的默认值:

public class InspectArrayFormulaArgs {

    private final int expectedColumns;

    @JsonCreator
    public InspectArrayFormulaArgs(
            @JsonProperty("expectedColumns")
            @JsonSetter(nulls = Nulls.SET, defaultValue = "-1") Integer expectedColumns) {
        this.expectedColumns = expectedColumns; // 此时expectedColumns不会为null
    }

}

注意:该方式要求Jackson版本≥2.9,@JsonSetter的nulls参数用于指定null值的处理策略,defaultValue会在字段缺失或为null时生效。

方法2:构造器内显式处理null(兼容低版本)

如果无法升级Jackson版本,可在构造器中手动处理null情况,同时保持字段为int类型:

public class InspectArrayFormulaArgs {

    private final int expectedColumns;

    @JsonCreator
    public InspectArrayFormulaArgs(@JsonProperty("expectedColumns") Integer expectedColumns) {
        this.expectedColumns = expectedColumns != null ? expectedColumns : -1;
    }

}

该方式逻辑清晰,兼容所有Jackson版本,唯一的不足是需要手动判断null。

方法3:全局开启USE_DEFAULT_VALUES特性

通过ObjectMapper开启全局默认值使用特性,这样Jackson会在字段缺失时自动应用@JsonProperty的defaultValue:

ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.USE_DEFAULT_VALUES);

实体类可保持原有的int类型构造器参数,但注意:该特性是全局生效的,会影响所有POJO的解析逻辑,仅当字段未被显式赋值时才会触发默认值。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 22:43:19