Jackson定制过滤器,具有完整的POJO数据绑定 [英] Jackson custom filter with full POJO data bind

查看:475
本文介绍了Jackson定制过滤器,具有完整的POJO数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题扩展了这个问题

如果您只有几个字段,之前的解决方案效果很好,那么当您有十几个字段时,它就变得无法维护。现在,我当前的设置使用完整的数据绑定,所以我有一个POJO,Jackson将使用它来自动反序列化JSON。

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.

但是,和以前一样,某些字段具有需要传递的约束。基本上,我正在寻找类似于这个,但不需要设置任何属性。只是一个自定义反序列化器,它将充当过滤器,并在字段不符合约束时抛出自定义异常。如果过滤器结束时没有抛出任何异常,Jackson应自动将JSON绑定到POJO。

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.

推荐答案

好像是 Json架构可能符合您的需求。它允许json字符串的灵活(和复杂)验证规则在反序列化之前。它包括必填字段,基于正则表达式的值检查,行业标准格式(例如,您可以将字段定义为电子邮件格式),跨字段依赖项(在最新的v4中)等等。

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

以上是与语言无关的标准。至于Java实现,我使用了这一个,它支持最新的json架构版本(标准是仍在不断发展)。验证器的初始集成是很多工作,(因为我非常动态的json模型)但是之后引入新的验证规则非常方便(只需要更改json模式文件)

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)

这篇关于Jackson定制过滤器,具有完整的POJO数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆