[英]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例如我的 POJO 有两个字段
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.如果传入的请求正文如下所示,则 hibernate 不会抛出任何错误,因为所有必填字段都在那里。
{
"firstName": "cat",
"lastName": "dog",
"extraField": "whatever"
}
Is there any way I can tell hibernate to check this kind of scenario?有什么办法可以告诉 hibernate 检查这种情况吗? I know I can just @JsonCreator
to do the trick.我知道我可以通过@JsonCreator
来解决问题。 But is it the good approach to combine both hibernate and Jackson together?但是将 hibernate 和 Jackson 结合在一起是不是一个好方法?
If you are using auto configuration then the following property in application.properties will do the trick.如果您使用自动配置,那么 application.properties 中的以下属性就可以解决问题。
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
我做了一个没有 spring 的小测试,它抛出异常com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.