获取jackson的未知领域列表

我有一个JSON模式和一个匹配模式的json字符串,除了它可能有一些额外的字段。 如果我没有添加objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);那么如果那些字段存在,jackson将抛出exceptionobjectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); 。 有没有办法获取这些额外字段的集合来记录它们,即使我抛出exception?

这是代码的相关位:

 public boolean validate(Message json) { List 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)中,如本文和本文所示 。

将其添加到Update类:

  private Map other = new HashMap(); @JsonAnyGetter public Map any() { return other; } @JsonAnySetter public void set(String name, String value) { other.put(name, value); } 

如果额外字段列表不为空,您可以自己抛出exception。 检查的方法是:

  public boolean hasUnknowProperties() { return !other.isEmpty(); } 

如果您只是想知道第一个未知属性(名称)是什么,我认为您获得的exception确实引用了该属性名称。 由于处理在第一个未知属性处停止(或者,如果忽略,则跳过该值),您将无法获得更多信息。

建议使用@JsonAnySetter是一个不错的选择。