Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 897
THIS USER NEEDS HELP Avatar asked Sep 20 '16 21:09

THIS USER NEEDS HELP


3 Answers

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)

like image 186
Sharon Ben Asher Avatar answered Nov 15 '22 14:11

Sharon Ben Asher


I would recommend to separate concerns for deserialization and validation by using Jackson and Hibernate Vaildator correspondingly. The idea is first to deserialize json data into POJO, and then validate the POJO according to the requirement. In you case, you can apply Class level constraints for validation. Class level constraints have a lot of flexibility and can validate multiple correlated properties by accessing the object instance. It is simple yet powerful.

Usually validation need more high level concerns. It is better to handle this after desrialization. Doing this can make the code more easily to manage and reuse the POJO and validation rules.

like image 31
Wilson Avatar answered Nov 15 '22 14:11

Wilson


just to consider: if you don't care about validation during deserialization, try the @JsonIgnoreProperties(ignoreUnknown = true) annotation for you POJO class. You can do the validation later where actual business logic works with pojo classes.

like image 36
Olesia Avatar answered Nov 15 '22 12:11

Olesia