简体   繁体   中英

Get list of unknown fields from 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;
}

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(); } 

If you simply want to know what the first unknown property (name) is, I think the exception you get does have reference to that property name. You won't be able to get more information since processing stops at the first unknown property (or, if ignoring, that value is skipped).

Use of @JsonAnySetter which was suggested is a good option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM