如何在Spring Boot响应控制中删除对象的某些字段?

bit*_*xyz 4 spring-boot

这是我的 REST 控制器之一,

@RestController
@RequestMapping("/users/Ache")
public class Users {
    @GetMapping
    public User getUser() {
        User user = new User();
        return user;
    }
}
Run Code Online (Sandbox Code Playgroud)

作为响应,Spring boot 会将我的对象转换为 JSON,这是响应:

{
    "username": "Ache",
    "password": "eee",
    "token": "W0wpuLAUQCwIH1r2ab85gWdJOiy2cp",
    "email": null,
    "birthday": null,
    "createDatetime": "2019-03-15T01:39:11.000+0000",
    "updateDatetime": null,
    "phoneNumber": null
}
Run Code Online (Sandbox Code Playgroud)

我想删除passwordtoken字段,我该怎么办?

我知道两个困难的方法:

  • 创建一个新的哈希图

    并添加一些必要的字段,但它太复杂了

  • 将这两个字段设置为 null
    但仍然留下两个 null 值字段,这太难看了。

有更好的解决办法吗?

fra*_*ayz 12

Spring 默认利用 Jackson 库进行 JSON 编组。我想到的最简单的解决方案是使用 Jackson 的 @JsonIgnore,但这会忽略序列化和反序列化的属性。因此,正确的方法是用 注释该字段@JsonProperty(access = Access.WRITE_ONLY)

例如,在假设的 User 类中:

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

@JsonProperty(access = Access.WRITE_ONLY)
private String token;
Run Code Online (Sandbox Code Playgroud)

另一种选择是@JsonIgnore仅在 getter 上使用:

@JsonIgnore
public String getPassword() {
    return this.password;
}
Run Code Online (Sandbox Code Playgroud)

您还可以创建另一个类,例如使用除和UserResponse之外的所有字段,并将其设为您的返回类型。当然,它涉及创建一个对象并填充它,但是您可以在没有 Jackson 注释的情况下让您的类保持干净,并将您的模型与表示分离。passwordtokenUser