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

Spring Boot中如何让@JsonIgnore字段可接收前端赋值并存储

问题:POST请求无法映射ip字段但需隐藏GET返回的ip值

问题场景

在Spring Boot 2.7.8环境下,定义了Participant实体类,期望前端通过POST接口传递的ip字段能存入数据库,但后端接收后该字段值始终为null。为了让GET接口返回结果不包含ip字段,给getIp()方法添加了@JsonIgnore注解,这部分生效了,但同时导致POST请求时ip字段无法被Jackson映射赋值。

实体类代码

import com.fasterxml.jackson.annotation.JsonIgnore;

@Entity
@Table(name="participant")
public class Participant {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long participantId; 
    private String ip;
    

    public void setIp(String ip) {
        this.ip = ip;
    }

    @JsonIgnore
    public String getIp(){return this.ip;}
    
}

REST控制器代码

@RequestMapping(value = "api/test", method = RequestMethod.POST)
public ResponseEntity<?> addParticipant(@RequestBody Participant p) {
    // 业务逻辑
}

前端请求载荷

{
  "ip": "172.1.1.1"
}

后端接收结果

{
  "ip": null
}

原因分析

@JsonIgnore注解会同时作用于序列化(GET接口返回对象转JSON)和反序列化(POST请求JSON转对象)过程。将该注解添加在getIp()方法上,不仅会在序列化时忽略ip字段,还会在反序列化时跳过对ip字段的赋值操作,导致后端接收不到前端传递的ip值。

解决方案

方案一:使用@JsonProperty(access = WRITE_ONLY)

将@JsonIgnore替换为@JsonProperty(access = JsonProperty.Access.WRITE_ONLY),该配置表示ip字段仅允许写入(反序列化),不允许读出(序列化),正好满足需求。

修改后的实体类代码:

import com.fasterxml.jackson.annotation.JsonProperty;

@Entity
@Table(name="participant")
public class Participant {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long participantId; 
    private String ip;
    

    public void setIp(String ip) {
        this.ip = ip;
    }

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    public String getIp(){return this.ip;}
    
}

方案二:字段加@JsonIgnore,set方法加@JsonProperty

在ip字段上添加@JsonIgnore实现序列化时隐藏,同时在setIp()方法上添加@JsonProperty("ip"),确保反序列化时能通过set方法为ip字段赋值。

修改后的实体类代码:

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

@Entity
@Table(name="participant")
public class Participant {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long participantId; 
    
    @JsonIgnore
    private String ip;
    
    @JsonProperty("ip")
    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getIp(){return this.ip;}
    
}

以上两种方案均可实现:POST请求时正常接收并赋值ip字段,GET接口返回结果中不包含ip字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 05:47:26