I’m trying to send PUT request and I want to check if there’re some extra fields. Is there any chance to check these extra fields, so I can throw an exception?
For example, I’ve got this JSON file and this one is okay to add
"id": 9999,
"name": "Film Updated",
"description": "New film update decription",
"releaseDate": "1989-04-17",
"duration": 190
As you can see, in the following file, there’s an extra field rate
"id": 9999,
"name": "Film Updated",
"releaseDate": "1989-04-17",
"description": "New film update decription",
"duration": 190,
"rate": 4
So I want to check if PUT request contains any extra fields to prevent from putting this information into HashMap. The following method is putting information into HashMap
@PostMapping(value = "/films")
public Film create(@Valid @RequestBody Film film) {
if (film.getDuration() <= 0
|| film.getReleaseDate().isBefore(FILM_DATE)
|| film.getDescription().length() > 200 || film.getName().isEmpty()) {
throw new ValidationException("Incorrect data");
} else {
if (film.getId() == 0) {
film.setId(1);
}
log.info("'{}' movie was added to a library, the identifier is '{}'", film.getName(), film.getId());
films.put(film.getId(), film);
}
return film;
}
But I have no idea how to check extra fields. Any ideas?
2
Answers
As far as i can see, you dont want to use extra properties from JSON? The best option for that is to create DTO object only with properties that you want to use called for example "FilmDTO" with @JsonIgnoreProperties(ignoreUnknown=true) class annotation.
I would also recommend not to put all the logic inside of Controller Class, try to create for example "FilmService" which will encapsulate whole business logic inside:
Controller:
Film
FilmDto
FilmService
This will throw an exception that you can gracefully handle. However, you might want to move the processFilm method to a service class.