I am trying to validate a JSON body within a post method. Here is a sample code:
@PostMapping(value = "GetInfo")
public ResponseEntity<Person> getOffers(@Valid @RequestBody InfoRequest infoRequest) {
//generate person response according to inforequest JSON.
Person person = PersonGenerator.getOffers(infoRequest);
return new ResponseEntity<>(person, HttpStatus.OK);
}
When I send JSON body to get info (for ex: Name
and Age
) I want the program to throw an error if some extra fields are entered that are not needed for the Person
class. As an example in below ExtraField
. But @RequestBody
and @Valid
annotations are just checking for fields that have a match. Since it is filtered (afaik in this case ExtraField
is filtered) I can't get full JSON to analyze infoRequest
to find if any extra information was sent.
{
"Name": "sample",
"Age": "sample",
"ExtraField": "prevent",
}
I know there are some libraries to check JSON files. But first I have to know what is coming :). If there is no annotation to see extra fields entered. How can I extract and analyze JSON file*
Note: Changing parameter type infoRequest
as String is not an option for security purposes.
CodePudding user response:
By default, the Spring Boot configuration will disables Jackson DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
feature. One possible solution could be enabling it again in you application.yml
file as follows:
spring.jackson.deserialization.fail-on-unknown-properties=true
This will change the behaviour for Jackson ObjectMapper
if you want finer-grained configuration you might use @JsonIgnoreProperties(ignoreUnknown = false)
as follows:
@JsonIgnoreProperties(ignoreUnknown = false)
public class InfoRequest {
(...)
}