问题
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.
回答1:
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)
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/39603910/jackson-custom-filter-with-full-pojo-data-bind