Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list of unknown fields from Jackson

Tags:

java

json

jackson

I have a JSON schema, and a json string that matches the schema, except it might have a few extra fields. Jackson will throw an exception if those fields are there if I don't add 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;
}
like image 555
Tavo Avatar asked Jun 17 '15 14:06

Tavo


1 Answers

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.

Add this to your Update class:

  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();
  }
like image 59
Laurentiu L. Avatar answered Sep 27 '22 16:09

Laurentiu L.