我有一个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;
}
Run Code Online (Sandbox Code Playgroud)
Lau*_* L. 11
我不认为有这样的选择开箱即用.
但是,您可以将@JsonAnyGetter和@JsonAnySetter中的这些未知字段保存在地图(Hashmap,Treemap)中,如本文和本文所示.
将其添加到Update类:
Run Code Online (Sandbox Code Playgroud)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); }
如果额外字段列表不为空,您可以自己抛出异常.检查的方法是:
Run Code Online (Sandbox Code Playgroud)public boolean hasUnknowProperties() { return !other.isEmpty(); }
| 归档时间: |
|
| 查看次数: |
3248 次 |
| 最近记录: |