@JsonProperty / @JsonIgnore在write-only属性上没有按预期工作

时间:2018-03-24 20:41:20

标签: spring-boot jackson

根据建议here我尝试在@JsonIgnore@JsonProperty字段上使用import com.fasterxml.jackson.annotation.*;password(来自passwordSalt)我的AppUser

@Entity
@Table(name = "app_user")
public class AppUser extends AbstractTimestampEntity {

    // ..

    @JsonIgnore
    public String getPassword() {
        return password;
    }

    @JsonProperty
    public void setPassword(String password) {
        this.password = password;
    }

    @JsonIgnore
    public String getPasswordSalt() {
        return passwordSalt;
    }

    @JsonProperty
    public void setPasswordSalt(String passwordSalt) {
        this.passwordSalt = passwordSalt;
    }

}

但是,出于某种原因,这两个字段始终为null。当我尝试“注册”用户时,我发送的JSON没有完全反序列化。 password设置为null

enter image description here

我想要实现的是能够接收用户的密码以便存储它,但同时确保存储的(加密的)密码没有被序列化并且也被发送回客户端。

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

对于Jackson版本2.9.0,以下内容适用于我:

@NoArgsConstructor
@AllArgsConstructor
public class Credentials {
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @JsonProperty(access = Access.WRITE_ONLY)
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

......还有正在运行的测试示例......

@Test
public void jsonIgnoreSerialization() throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();

    String serialized = objectMapper.writeValueAsString(new Credentials("user", "pass"));
    assertThat(serialized).isEqualTo("{\"username\":\"user\"}");

    Credentials credentials = objectMapper.readValue("{\"username\":\"user\",\"password\":\"pass\"}", Credentials.class);
    assertThat(credentials.getUsername()).isEqualTo("user");
    assertThat(credentials.getPassword()).isEqualTo("pass");
}

为简单起见,构造函数是来自Lombok的构造函数,而断言来自AssertJ

你可以尝试一下吗?