获取杰克逊的未知领域列表 [英] Get list of unknown fields from Jackson
问题描述
我有一个JSON模式,以及一个与模式匹配的json字符串,除了它可能有一些额外的字段。如果我不添加 objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
,杰克逊将抛出异常,如果那些字段在那里。有没有办法获取这些额外字段的集合来记录它们,即使我抛出异常?
I have a JSON schema, and a json string that matches the schema, except it might have a few extra fields. Jackson will throw an exception if those fields are there if I don't add objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
. Is there a way to obtain a collection of those extra fields to log them, even if I throw an exception?
这是代码的相关位:
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;
}
推荐答案
我认为没有开箱即用的这样一个选项。
I don't think there's such an option out of the box.
然而,您可以将@JsonAnyGetter和@JsonAnySetter中的这些未知字段保存在地图(Hashmap,Treemap)中,如本文和这一个。
You could however keep these unkwown fields with @JsonAnyGetter and @JsonAnySetter in a map (Hashmap,Treemap) as exemplified in this article and this one.
将此添加到您的Update类:
Add this to your Update class:
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);
}
你可以自己抛出异常额外字段列表不为空。检查的方法:
And you can throw an exception yourself if the extra fields list is not empty. The method for checking that:
public boolean hasUnknowProperties() {
return !other.isEmpty();
}
这篇关于获取杰克逊的未知领域列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!