Search code examples
javajsonjacksonpojojackson2

Jackson custom filter with full POJO data bind


This question extends this question.

While the previous solution works great if you only have a couple of fields, it becomes unmaintainable when you have more than a dozen of fields. Right now, my current set up uses full data binding, so I have a POJO that will be used by Jackson to automatically deserialize JSON.

However, as before, certain fields have constraints that need to pass. Essentially, I am looking for an answer similar to this, but without the need to set any properties. Just a custom deserializer that will act as a filter and throw a custom exception if a field does not meet the constraint. If no exception has been thrown by the end of the filter, Jackson should automatically bind JSON to POJO.


Solution

  • Seems like Json Schema might fit your needs. It allows for flexible (and complex) validation rules of json strings before they are deserialized. It includes mandatory fields, regex-based value check, industry-standard formats (for instance, you can define a field as "email" format), cross-field dependencies (in latest v4), etc

    The above is language-independant standard. As for Java implemenation, I used this one which supports latest json schema version (the standard is still evolving). The initial integration of the validator was a lot of work, (becasue of my very-dynamic json model) but after that it is very convinient to introduce new validation rules (just need to change json schema file)