使用@JsonIgnore遇到的问题

今天使用到了@JsonIgnore这一注解,记录一下遇到的问题。

项目背景:这是一个springboot+vue前后端分离的项目,其中有一个功能是新增用户,前端post请求提交用户表单数据,后端在Controller层使用@RequestBody+实体类User进行接收,user中包含用户名,密码等信息。

问题描述:在接收时发现密码字段得到的是空值,其他数据均为正常接收,

问题定位:我已确认前端把所有数据都传过来了,所以问题定位在后端这里,然后我将接收的实体类User改为Map接收,数据都能正常接收到,然后我去查看了User实体类,发现实体类User中密码password字段的getter函数上标有@JsonIgnore这一注解,于是我对这一注解进行了查看,发现这一注解的作用,是在json序列化时,将java bean中的一些属性忽略掉,可以使用在属性或方法上,比如我的项目中把它用在了getter方法上,产生的效果就是当响应某个user对象时,就不会把密码字段响应出去;但是会有一个问题,这样一来,当使用@RequestBody接收json格式的user对象时,会把password字段也忽略掉,这不是我想要的

问题解决:在相应的setter方法上加上@JsonProperty注解即可

具体原因可查看@JsonIgnore的源码注释:

Annotation only needs to be added to one of the accessors (often

  • getter method, but may be setter, field or creator parameter),
  • if the complete removal of the property is desired.
  • However: if only particular accessor is to be ignored (for example,
  • when ignoring one of potentially conflicting setter methods),
  • this can be done by annotating other not-to-be-ignored accessors
  • with {@link JsonProperty} (or its equivalents). This is considered
  • so-called “split property” case and allows definitions of
  • “read-only” (read from input into POJO) and “write-only” (write
  • in output but ignore on output)
    *

json过滤某些属性之@jsonignore

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值