我有一个 JSON 架构和一个与该架构匹配的 json 字符串,但它可能有一些额外的字段。如果我不添加这些字段,杰克逊将抛出异常objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
。有没有办法获取这些额外字段的集合来记录它们,即使我抛出异常?
这是代码的相关部分:
public boolean validate(Message<String> json) {
List<String> errorList = jsonSchema.validate(json.getPayload());
ObjectMapper mapper = new ObjectMapper();
try {
Update update = mapper.readValue(json.getPayload(), Update.class);
} catch (IOException e) {
System.out.println("Broken");
}
if(!errorList.isEmpty()) {
LOG.warn("Json message did not match schema: {}", errorList);
}
return true;
}
我不认为有这样的现成选项。
但是,您可以使用 @JsonAnyGetter 和 @JsonAnySetter 将这些未知字段保留在地图(Hashmap、Treemap)中,如下所示本文 http://vincentdevillers.blogspot.ro/2013/08/how-to-map-unknown-json-properties-with.html and this one http://demeranville.com/deserialising-json-or-xml-to-a-map-using-java/.
将其添加到您的 Update 类中:
private Map<String, String> other = new HashMap<String, String>();
@JsonAnyGetter
public Map<String, String> any() {
return other;
}
@JsonAnySetter
public void set(String name, String value) {
other.put(name, value);
}
如果额外字段列表不为空,您可以自己抛出异常。检查方法:
public boolean hasUnknowProperties() {
return !other.isEmpty();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)