[英]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.