有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java春季休息。消除HTTP上的json属性。邮递

我试图排除在HTTP上修改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,但它不起作用,相反,它适用于密码字段。(此属性仅对写入/发布可见)

你能告诉我哪里错了吗?或者有没有更优雅的方法

非常感谢,


共 (1) 个答案

  1. # 1 楼答案

    您可以通过@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