我正在使用ObjectMapper(Jackson)将我的API JSON响应映射到Java对象。以下是我的json的样子:
[
{
firstKey : "value1",
secondKey : "value2",
thirdKey : "value3"
},
{
firstKey : "value4",
secondKey : "value5",
thirdKey : "value6"
}
]
必填字段为: firstKey secondKey thirdKey
我的某些JSON响应可能没有这三个必填字段,我想让Jackson在反序列化时抛出异常。我应该如何让Jackson知道必填字段?除了JsonProperty(required = true)之外,是否还有其他注释,因为这不起作用?
此外,如果键的值为空,则它是默认值,因此我也不能使用@NotNull。例如: [ { firstKey:null, secondKey:“ value2”, thirKey:“ value3” } ] 上面是有效的JSON,在反序列化过程中应毫无例外地进行解析。
答案 0 :(得分:0)
Jackson并未实现验证功能的整体,因为它被认为不在范围内,例如参见Jackson - Required property?。
有关批注@JsonProperty(required = true)
为何在字段上不起作用的一些信息,可以在这里找到:Jackson @JsonProperty(required=true) doesn't throw an exception。
但是,有一种技巧可能适用于null
和现有的有价值的字段值,但是如果该字段完全丢失,则会引发异常。使用注解@JsonCreator
创建一个带有注释@JsonProperty(value = "*field_name*", required = true)
的构造函数(并且不要创建默认构造函数!),其中使用相同的注释@Getter @Setter
public class KeyHolder {
private String firstKey;
private String secondKey;
private String thirdKey;
@JsonCreator
public KeyHolder(
@JsonProperty(value = "firstKey", required = true) String firstKey,
@JsonProperty(value = "secondKey", required = true) String secondKey,
@JsonProperty(value = "thirdKey", required = true) String thirdKey) {
this.firstKey = firstKey;
this.secondKey = secondKey;
this.thirdKey = thirdKey;
}
}
,并且在缺少字段的情况下会抛出该异常,例如:
new ObjectMapper().readValue("{ \"firstKey\": \"val1\", \"secondKey\": \"val2\" }"
, KeyHolder.class);
通过这些操作:
set := 8 getAllMethods
应该导致类似以下内容:
com.fasterxml.jackson.databind.exc.MismatchedInputException:缺少必需的创建者属性“ thirdKey”(索引2)