【问题标题】:Spring Rest. Eliminate json property at HTTP.POST春天休息。消除 HTTP.POST 的 json 属性
【发布时间】:2018-07-26 13:13:20
【问题描述】:

我试图排除在 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 但它不起作用,而是适用于 password 字段。 (此属性仅对 write/post 可见)。

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

非常感谢,

【问题讨论】:

  • This 应该会有所帮助。
  • 谢谢,@AndrewS,我仍在寻找另一种解决方案。如您所见,我使用 lombok,并且不想为域类编写构造函数。

标签: java jackson spring-rest jackson-dataformat-xml


【解决方案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

【讨论】:

    猜你喜欢
    • 2013-06-17
    • 2011-09-23
    • 2013-12-13
    • 1970-01-01
    • 2013-01-29
    • 2014-10-09
    • 2010-10-06
    • 2011-07-13
    • 1970-01-01
    相关资源
    最近更新 更多