2

我试图排除在 HTTP.POST 操作中修改 json 字段的可能性。这是我的课:

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class UserModel {

    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    private Long userId;

    @NotNull
    private String username;

    private RoleModel role;

    @NotNull
    private String email;

    @NotNull
    private String firstName;

    @NotNull
    private String secondName;

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

    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    private Date registrationDate;
}

例如,我希望属性userId只能用于读取(http get)。我尝试过使用@JsonProperty,但它不起作用,而是适用于密码字段。(此属性仅对 write/post 可见)。

你能告诉我我哪里错了吗?或者是否有更优雅的方式来做到这一点?

非常感谢,

4

1 回答 1

2

您可以使用 @JsonView 注释来实现这样的事情:

// Declare views as you wish, you can also use inheritance.
// GetView also includes PostView's fields 
public class View {
    interface PostView {}
    interface GetView extends PostView {}
}

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class UserModel {

    @JsonView(View.GetView.class)
    private Long userId;

    @JsonView(View.PostView.class)
    @NotNull
    private String username;
    ....
}

@RestController
public class Controller {

    @JsonView(View.GetView.class)
    @GetMapping("/")
    public UserModel get() {
        return ... ;
    }

    @JsonView(View.PostView.class)
    @PostMapping("/")
    public UserModel post() {
        return ... ;
    }

...
}

欲了解更多信息:https ://spring.io/blog/2014/12/02/latest-jackson-integration-improvements-in-spring

于 2018-02-18T19:50:42.377 回答