Jackson how to Fail on NO KNOWN properties - unlike DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES

560 Views Asked by At

We are using Jackson XmlMapper and ObjectMapper for parsing XML and JSON files into object models in Java.

Problem is, we are also using them to validate (by catching xmlMapper.readValue(file, type) returning IOExeception, that the file given to parse, matches the model (so long as the required model fields are there, we dont care about unknown properties - as long as the whole object wouldn't be returned as null in all its properties.

So, using xmlMapper.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) does not quite work for us, as it fails the mapping if there are unknown attributes we did not care to map (or know about, or they don't always show up).

However, we STILL would like the mapping to fail, IF the object we are mapping to, becomes null (eg: the xml file given to map, is not at all like the correct structure - eg: it starts with as root element, while the model we are mapping to, starts with element, and doesn't have "pages" anywhere in the XML.

The main class for the model, is annotated as: @JacksonXmlRootElement(localName = "ResultsSession"), and all attributes we need are annotated as @JacksonXmlProperty(localName = "someValue"), or (isAttribute = true)

Does this make sense? Is there a way to make sure the mapped object contains the root element, without forcing fail or unknown properties?

1

There are 1 best solutions below

0
On

I found an acceptable solution which works well. The correct way of doing it, is though Java Bean Validator, something along the lines of:

ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();
Set<ConstraintViolation<Object> violations = validator.validate(mappedObject);
if (violations.size > 0 ) {
  for (ConstraintViolation<Object> violation : violations( {
    LOGGER.error(violation.getMessage());
  }
}

And the Object being validated, would have added something like: @NotNull(Message = "error message") to a key attributes, and that will work nicely.

Reference: https://www.baeldung.com/javax-validation