问题描述
我有一个发送到服务器和从服务器发送的用户对象.当我发送用户对象时,我不想将散列密码发送给客户端.因此,我在 password 属性上添加了 @JsonIgnore
,但这也阻止了它被反序列化为密码,这使得在用户没有密码时难以注册.
I have a user object that is sent to and from the server. When I send out the user object, I don't want to send the hashed password to the client. So, I added @JsonIgnore
on the password property, but this also blocks it from being deserialized into the password that makes it hard to sign up users when they don't have a password.
我怎样才能只让 @JsonIgnore
应用于序列化而不是反序列化?我使用的是 Spring JSONView,所以我对 ObjectMapper
没有太多控制权.
How can I only get @JsonIgnore
to apply to serialization and not deserialization? I'm using Spring JSONView, so I don't have a ton of control over the ObjectMapper
.
我尝试过的事情:
- 在属性中添加
@JsonIgnore
- 只在getter方法上添加
@JsonIgnore
推荐答案
具体如何执行此操作取决于您使用的 Jackson 版本.这在版本 1.9 前后发生了变化,在此之前,您可以通过将 @JsonIgnore
添加到 getter 来实现.
Exactly how to do this depends on the version of Jackson that you're using. This changed around version 1.9, before that, you could do this by adding @JsonIgnore
to the getter.
您尝试过的:
只在getter方法上添加@JsonIgnore
这样做,并为您的 JSON密码"添加一个特定的 @JsonProperty
注释;对象上密码的 setter 方法的字段名称.
Do this, and also add a specific @JsonProperty
annotation for your JSON "password" field name to the setter method for the password on your object.
最新版本的 Jackson 为 JsonProperty
添加了 READ_ONLY
和 WRITE_ONLY
注释参数.因此,您还可以执行以下操作:
More recent versions of Jackson have added READ_ONLY
and WRITE_ONLY
annotation arguments for JsonProperty
. So you could also do something like:
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
可以找到文档这里.
这篇关于仅在序列化期间使用@JsonIgnore,而不是反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!