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

Jackson反序列化:将JSON字段映射至内部对象并正确序列化

解决Jackson反序列化映射到内部对象且序列化仅输出内部对象的问题

核心是通过Jackson的注解分别控制反序列化的字段映射逻辑,以及序列化的输出内容,无需自定义反序列化器。

步骤1:定义内部Scores类

public class Scores {
    private int score;

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }
}

步骤2:编写MyObject类的正确注解配置

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

public class MyObject {
    private Scores scoreObject = new Scores();

    // 显式指定该方法对应JSON中的"score"字段,反序列化时自动调用赋值
    @JsonProperty("score")
    public void setScore(int score) {
        this.scoreObject.setScore(score);
    }

    // 序列化时忽略该方法,避免输出额外的"score"字段
    @JsonIgnore
    public int getScore() {
        return this.scoreObject.getScore();
    }

    // 序列化时输出内部的scoreObject对象
    @JsonProperty("scoreObject")
    public Scores getScoreObject() {
        return scoreObject;
    }

    // 禁止外部直接设置scoreObject,序列化时也忽略该方法
    @JsonIgnore
    public void setScoreObject(Scores scoreObject) {
        this.scoreObject = scoreObject;
    }
}

步骤3:验证效果

测试代码如下:

import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTest {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();

        // 反序列化测试:JSON的score值会存入内部scoreObject
        String inputJson = "{\"score\":123}";
        MyObject obj = mapper.readValue(inputJson, MyObject.class);
        System.out.println(obj.getScoreObject().getScore()); // 输出:123

        // 序列化测试:仅输出内部的scoreObject字段
        String outputJson = mapper.writeValueAsString(obj);
        System.out.println(outputJson); // 输出:{"scoreObject":{"score":123}}
    }
}

为什么之前的方案失效?

之前仅给getScore()加@JsonIgnore时,Jackson会默认忽略对应的setScore()方法(因为它会将getter/setter视为一组字段),导致反序列化时无法映射JSON的score值。通过给setScore()显式添加@JsonProperty("score"),可以强制Jackson识别该方法对应的JSON字段,不受getScore()上@JsonIgnore的影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 03:48:16