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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With