获取杰克逊的未知领域列表

Tav*_*avo 6 java json jackson

我有一个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类:

  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();
  }
Run Code Online (Sandbox Code Playgroud)

  • @Tavo扩展Update类. (2认同)