[英]Get list of unknown fields from Jackson
I have a JSON schema, and a json string that matches the schema, except it might have a few extra fields. 我有一个JSON模式和一个匹配模式的json字符串,除了它可能有一些额外的字段。 Jackson will throw an exception if those fields are there if I don't add
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
如果我不添加
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
那么如果那些字段在那里,杰克逊将抛出异常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?
有没有办法获取这些额外字段的集合来记录它们,即使我抛出异常?
Here's the relevant bit of the code: 这是代码的相关位:
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. 我不认为有这样的选择开箱即用。
You could however keep these unkwown fields with @JsonAnyGetter and @JsonAnySetter in a map (Hashmap,Treemap) as exemplified in this article and this one . 但是,您可以将@JsonAnyGetter和@JsonAnySetter中的这些未知字段保存在地图(Hashmap,Treemap)中,如本文和本文所示 。
Add this to your Update class: 将其添加到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); }
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(); }
If you simply want to know what the first unknown property (name) is, I think the exception you get does have reference to that property name. 如果您只是想知道第一个未知属性(名称)是什么,我认为您获得的异常确实引用了该属性名称。 You won't be able to get more information since processing stops at the first unknown property (or, if ignoring, that value is skipped).
由于处理在第一个未知属性处停止(或者,如果忽略,则跳过该值),您将无法获得更多信息。
Use of @JsonAnySetter
which was suggested is a good option. 建议使用
@JsonAnySetter
是个不错的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.