我有一个从服务器发送到服务器的用户对象。当我发送用户对象时,我不想将散列后的密码发送给客户端。因此,我在password属性上添加了@JsonIgnore,但这也阻止了它被反序列化为密码,这使得在用户没有密码时很难注册用户。

我怎么能只得到@JsonIgnore应用于序列化而不是反序列化?我使用的是Spring JSONView,所以我对ObjectMapper没有太多的控制。

我尝试过的事情:

向属性中添加@JsonIgnore 只在getter方法上添加@JsonIgnore


当前回答

你还可以这样做:

@JsonIgnore
@JsonProperty(access = Access.WRITE_ONLY)
private String password;

这对我很有效

其他回答

理想的解决方案是使用DTO(数据传输对象)

具体如何做到这一点取决于您正在使用的Jackson版本。这在1.9版本左右发生了变化,在那之前,您可以通过向getter添加@JsonIgnore来做到这一点。

你已经试过了:

只在getter方法上添加@JsonIgnore

这样做,还为JSON“password”字段名添加一个特定的@JsonProperty注释,将其添加到对象上的密码setter方法。

Jackson的最新版本为JsonProperty添加了READ_ONLY和WRITE_ONLY注释参数。所以你也可以这样做:

@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;

文档可以在这里找到。

你可以在类级别使用@JsonIgnoreProperties,并将你想忽略的变量放在json的“value”参数中。对我来说还不错。

@JsonIgnoreProperties(value = { "myVariable1","myVariable2" })
public class MyClass {
      private int myVariable1;,
      private int myVariable2;
}

你还可以这样做:

@JsonIgnore
@JsonProperty(access = Access.WRITE_ONLY)
private String password;

这对我很有效

为了实现这一点,我们只需要两个注释:

@JsonIgnore @JsonProperty

在类成员及其getter上使用@JsonIgnore,在类成员的setter上使用@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;
    }
}