chu*_*ubs 298 java spring json annotations jackson
我有一个发送到服务器和从服务器发送的用户对象.当我发出用户对象时,我不想将散列密码发送给客户端.所以我添加@JsonIgnore
了密码属性,但这也阻止了它被反序列化为密码,这使得在没有密码时很难注册用户.
我怎样才能@JsonIgnore
应用于序列化而不是反序列化?我正在使用Spring JSONView,所以我没有很多控制权ObjectMapper
.
我试过的事情:
@JsonIgnore
物业@JsonIgnore
仅添加getter方法pb2*_*b2q 440
究竟如何做到这一点取决于你正在使用的杰克逊版本.这在版本1.9中发生了变化,在此之前,您可以通过添加@JsonIgnore
到getter 来实现此目的.
你试过的:
仅在getter方法上添加@JsonIgnore
执行此操作,并将@JsonProperty
JSON"密码"字段名称的特定注释添加到对象密码的setter方法中.
更新版本的杰克逊已添加READ_ONLY
和WRITE_ONLY
注释参数JsonProperty
.所以你也可以这样做:
@JsonProperty(access = Access.WRITE_ONLY)
private String password;
Run Code Online (Sandbox Code Playgroud)
可以在这里找到文档.
Bal*_*yan 94
为了实现这一点,我们需要的只是两个注释:
@JsonIgnore
@JsonProperty
使用@JsonIgnore
类成员和其吸气剂上.@JsonProperty
在其二传手上使用.
示例说明将有助于执行此操作:
class User {
// More fields here
@JsonIgnore
private String password;
@JsonIgnore
public String getPassword() {
return password;
}
@JsonProperty
public void setPassword(final String password) {
this.password = password;
}
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*eer 73
从版本2.6开始:更直观的方法是com.fasterxml.jackson.annotation.JsonProperty
在字段上使用注释:
@JsonProperty(access = Access.WRITE_ONLY)
private String myField;
Run Code Online (Sandbox Code Playgroud)
即使存在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
Run Code Online (Sandbox Code Playgroud)
如果您需要反过来,只需使用Access.READ_ONLY
.
Ale*_*ley 13
在我的情况下,我让Jackson自动序列化/反序列化我从Spring MVC控制器返回的对象(我在Spring 4.1.6中使用@RestController).我必须使用com.fasterxml.jackson.annotation.JsonIgnore
而不是org.codehaus.jackson.annotate.JsonIgnore
,否则它什么也没做.
小智 8
allowSetters = true
处理此问题的另一种简单方法是在注释中使用参数。这将允许密码反序列化到您的 dto 中,但不会将其序列化到使用 contains 对象的响应正文中。
例子:
@JsonIgnoreProperties(allowSetters = true, value = {"bar"})
class Pojo{
String foo;
String bar;
}
Run Code Online (Sandbox Code Playgroud)
和foo
都bar
填充在对象中,但只有 foo 写入响应正文中。
归档时间: |
|
查看次数: |
264685 次 |
最近记录: |