简体   繁体   中英

How can I tell Hibernate Validator to throw exception if the incoming request has less or extra fields than the POJO

For example my POJO has two field

public class User {
    @NotNull
    private String firstName;
    @NotNull
    private String lastName;
}

if the incoming request body is like the following, the hibernate won't throw any error, since all required field is there.

{
  "firstName": "cat",
  "lastName": "dog",
  "extraField": "whatever"
}

Is there any way I can tell hibernate to check this kind of scenario? I know I can just @JsonCreator to do the trick. But is it the good approach to combine both hibernate and Jackson together?

If you are using auto configuration then the following property in application.properties will do the trick.

spring.jackson.deserialization.fail-on-unknown-properties=true

This is equivalent to the following

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);

I did a small test without spring and it throws an exception com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM