我有一个 JSON 模式和一个与该模式匹配的 json 字符串,除了它可能有一些额外的字段。如果我不添加 objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false, false);
,那么如果存在这些字段,Jackson 将抛出异常。有没有办法获取这些额外字段的集合来记录它们,即使我抛出异常?
这是代码的相关部分:
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)中,如this article 中所示。和 this one .
将此添加到您的更新类:
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(); }
关于java - 从 Jackson 获取未知字段列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30894269/