繁体   English   中英

如果传入请求的字段少于或多于 POJO,我如何告诉 Hibernate 验证器抛出异常

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

例如我的 POJO 有两个字段

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

如果传入的请求正文如下所示,则 hibernate 不会抛出任何错误,因为所有必填字段都在那里。

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

有什么办法可以告诉 hibernate 检查这种情况吗? 我知道我可以通过@JsonCreator来解决问题。 但是将 hibernate 和 Jackson 结合在一起是不是一个好方法?

如果您使用自动配置,那么 application.properties 中的以下属性就可以解决问题。

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

这等价于以下

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);

我做了一个没有 spring 的小测试,它抛出异常com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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