与Jackson合作的@NotNull验证

时间:2017-09-27 15:51:10

标签: java jackson

当我发布到我的控制器 - 带有空值的json时,我遇到了可清除异常的问题。

ve set all fields as @NotNull. And it的工作正常(我看到了很好的异常消息:对象''on field''中的字段错误:被拒绝的值[null])。

不幸的是,带有@NotNull的集合字段会返回JsonMappingException。

例如:

  @Value
public final class User {

    @NotNull
    private final Integer age; //work fine


    @NotNull
    private final List<Books> books; //doesn`t work

ve also tried with @Valid and @NotEmpty, but it didn帮忙。

我的控制器方法:

@Timed
    @ExceptionMetered
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    @PreAuthorize("@auth.hasAccess(...)")
    void registerUser(@RequestBody @Valid User user) {
        userService.registerUser(user);
    }

你知道它有什么问题吗?

1 个答案:

答案 0 :(得分:1)

你试过两个吗?

@NotNull
@Valid
private final List<Books> books;

修改

Spring Version :1.4.7.RELEASE

图书:

public class Book {

    private String id;
    private String title;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

}

用户:

public class User {

    @NotNull
    private int age;

    @NotNull
    @Valid
    private List<Book> books;

    public int getAge() {
        return age;
    }

     public void setAge(int age) {
        this.age = age;
     }

     public List<Book> getBooks() {
         return books;
     }

     public void setBooks(List<Book> books) {
         this.books = books;
     }

 }

控制器:

@PostMapping("/")
public User post(@RequestBody @Valid User user) {
    return user;
}

试验:

curl -s -XPOST http://localhost:8080/ -d '{"age": 13, "books": [{"id": "test", "title": "test"}]}' -H "Content-Type:application/json" | python -m json.tool

{
  "age": 13,
  "books": [
    {
      "id": "test",
      "title": "test"
    }
   ]
}

curl -s -XPOST http://localhost:8080/ -d '{"age": 13}' -H "Content-Type:application/json" | python -m json.tool

{
   "error": "Bad Request",
   "errors": [...]
}

显然,没有错......