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

Spring Boot 1.5中Jackson用@JsonCreator序列化Bean需Getter方法的疑问

Spring Boot 1.5中Jackson配合@JsonCreator序列化Bean的注意事项

在Spring Boot 1.5的项目里用Jackson把Bean序列化为JSON时,如果你想让@JsonCreator正常工作,确实得满足两个关键条件:一是给每个属性声明Getter方法,二是在构造方法的参数上搭配@JsonProperty注解。

之所以需要Getter,是因为Jackson在序列化过程中,默认是通过Getter方法来读取Bean的属性值的——尤其是像示例里name和age这种final修饰的字段,没有Setter方法,只能依靠Getter来暴露属性内容。而@JsonCreator主要负责反序列化(把JSON转成Bean),但要保证序列化也能正常输出这些属性,Getter就必不可少了。

下面是完整的示例代码:

public class Person {
    private final String name;
    private final int age;

    @JsonCreator
    public Person(@JsonProperty("name") String name, @JsonProperty("age") int age) {
        this.name = name;
        this.age = age;
    }

    // 必须添加Getter才能让Jackson序列化时读取到属性
    public String getName() {
        return this.name;
    }

    public int getAge() {
        return this.age;
    }
}

如果省略了Getter方法,Jackson在序列化时会无法读取到final字段的值,最终输出的JSON可能会缺失这些属性;而如果构造方法参数上不加@JsonProperty,在反序列化时Jackson无法正确匹配JSON中的字段和构造方法的参数,会直接导致反序列化失败。

内容的提问来源于stack exchange,提问作者riccardo.cardin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:50:15