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

Jackson库:JSON转对象保留属性,对象转JSON忽略该属性

实现JSON反序列化保留id、序列化忽略id

需求说明

我有一个返回JSON格式数据的REST API:

  • 从API获取JSON时,需要读取其中的id属性做校验;
  • 向服务器回写数据(对象转JSON)时,响应JSON不能包含id属性;
  • 不能将id设为write-only,否则无法读取其值。

核心目标:JSON转对象时保留id,对象转JSON时忽略id。

原始示例代码

public class Product {
    
    // JSON转对象时需保留,对象转JSON时需忽略
    @JsonProperty
    public String id;
    
    @JsonProperty
    public String name;
   
}

示例数据

  • GET响应JSON(需正常解析到对象):
{
  "id": "1",
  "name": "Product1"
}
  • 错误的POST响应JSON(不应包含id):
{
  "id": "1",
  "name": "Product1"
}
  • 正确的POST响应JSON:
{
  "name": "Product1"
}

解决方案(基于Jackson注解)

方案1:使用@JsonProperty的access属性(简洁版)

直接在id字段上指定访问权限为WRITE_ONLY,表示该字段仅允许反序列化时写入(JSON→对象),序列化时不会输出(对象→JSON)。

import com.fasterxml.jackson.annotation.JsonProperty;

public class Product {
    // 反序列化时读取id,序列化时忽略id
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    public String id;
    
    @JsonProperty
    public String name;
}

方案2:拆分Getter/Setter注解(灵活版)

如果字段是私有属性,可通过给Setter加@JsonProperty、Getter加@JsonIgnore实现同样效果:

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

public class Product {
    private String id;
    private String name;

    // 反序列化时允许设置id
    @JsonProperty
    public void setId(String id) {
        this.id = id;
    }

    // 序列化时忽略id的读取
    @JsonIgnore
    public String getId() {
        return id;
    }

    // name字段正常读写
    @JsonProperty
    public String getName() {
        return name;
    }

    @JsonProperty
    public void setName(String name) {
        this.name = name;
    }
}

效果验证

  • 解析GET响应的JSON时,id会被正常赋值到Product对象中,可用于校验;
  • 将Product对象序列化为JSON时,输出结果不会包含id字段,符合POST响应的要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 05:20:29