问题
我有一个发送到服务器和从服务器发送的用户对象。当我发出用户对象时,我不想将散列密码发送给客户端。所以我在密码属性中添加了@JsonIgnore
,但这也阻止了它被反序列化为密码,这使得用户在没有密码时很难注册。
我怎样才能将4889789911应用于序列化而不是反序列化?我正在使用Spring JSONView,所以我对ObjectMapper
没有太大的控制权。
我尝试过的事情:
- 将@JsonIgnore添加到属性中
- 仅在getter方法上添加@JsonIgnore
#1 热门回答(312 赞)
究竟如何做到这一点取决于你正在使用的杰克逊版本。这在版本1.9之间发生了变化,在此之前,你可以通过将@JsonIgnore
添加到getter来实现此目的。
你尝试过的:
仅在getter方法上添加@JsonIgnore
执行此操作,并为你的JSON"密码"字段名称添加特定的@JsonProperty
注释,作为对象密码的setter方法。
更新版本的Jackson已为JsonProperty
添加了READ_ONLY
和WRITE_ONLY
注释参数。所以你也可以这样做:
@JsonProperty(access = Access.WRITE_ONLY)
private String password;
可以找到文件here。
#2 热门回答(71 赞)
为了实现这一点,我们需要的只是两个注释:
- @JsonIgnore
- @JsonProperty
使用@JsonIgnore
类成员及其getter。使用@JsonProperty
作为其二传手。
示例说明将有助于执行此操作:
class User{
// More fields here
@JsonIgnore
private String password;
@JsonIgnore
public String getPassword() {
return password;
}
@JsonProperty
public void setPassword(String password) {
this.password = password;
}
}
#3 热门回答(50 赞)
从版本2.6开始:更直观的方法是在字段上使用com.fasterxml.jackson.annotation.JsonProperty
注释:
@JsonProperty(access = Access.WRITE_ONLY)
private String myField;
即使存在getter,也会从序列化中排除字段值。
JavaDoc说:
/**
* Access setting that means that the property may only be written (set)
* for deserialization,
* but will not be read (get) on serialization, that is, the value of the property
* is not included in serialization.
*/
WRITE_ONLY
如果你需要反过来,只需使用466663326。