Reputation: 21
I have a problem with clearable exception when I post to my controller - json with nulls.
Ive set all fields as @NotNull. And it
s work fine (which null values I see nice exception with message: Field error in object '' on field '': rejected value [null]).
Unfortunately collections fields with @NotNull return JsonMappingException.
For example:
@Value
public final class User {
@NotNull
private final Integer age; //work fine
@NotNull
private final List<Books> books; //doesn`t work
Ive also tried with @Valid and @NotEmpty, but it didn
t help.
My controller method:
@Timed
@ExceptionMetered
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
@PreAuthorize("@auth.hasAccess(...)")
void registerUser(@RequestBody @Valid User user) {
userService.registerUser(user);
}
Do you know what is wrong with it?
Upvotes: 2
Views: 5227
Reputation: 1499
Did you try both?
@NotNull
@Valid
private final List<Books> books;
EDIT
Spring Version: 1.4.7.RELEASE
Book:
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;
}
}
User:
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;
}
}
Controller:
@PostMapping("/")
public User post(@RequestBody @Valid User user) {
return user;
}
Tests:
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": [...]
}
Apparently, nothing wrong...
Upvotes: 1