Get a list of unknown fields from Jackson

I have a JSON schema and a json string that matches the schema, except that it can contain a few extra fields. Jackson throws an exception if these fields exist, if I do not add objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); . Is there a way to get a collection of these extra fields to register them even if I throw an exception?

Here is the corresponding bit of 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; } 
+5
source share
2 answers

I don’t think there is such an option out of the box.

You could, however, have these unkwown fields with @JsonAnyGetter and @JsonAnySetter in the map (HashMap, TreeMap), as this article also illustrated in this article .

Add this to the 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 create an exception yourself if the additional list of fields is not empty. A method to verify that:

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

If you just want to know what the first unknown property (name) is, I think the exception you get has a link to that property name. You cannot get more information, because processing stops at the first unknown property (or, if ignored, this value is skipped).

Using @JsonAnySetter , which has been suggested, is a good option.

+2
source

All Articles