我正在使用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,在反序列化过程中应毫无例外地进行解析。
最佳答案
总体上,验证功能未在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);
应该导致类似:
com.fasterxml.jackson.databind.exc.MismatchedInputException:缺少必需的创建者属性“ thirdKey”(索引2)