only-json-validator是Java校验json数据类型的一个小框架,基于fastjson做json解析。
因为在做项目时,现在Java后台接口多半在body中使用json做为数据传输,但是没找到比较想要的一款验证json数据的框架。于是自己动手写了这么一个验证json数据的小框架,希望弄帮到大家。
使用方式:
示例需验验证的json字符串{"name":"张三","age":101,"email":"","sex":"男","head":"https://ssss","index":"b","roleIds":[1,2,6],"roles":[{"name":"经理","grade":"12"},{"name":"总监","grade":"13"}]}先写配置文件,配置文件中配置验证规则,配置在json文件中[//数组为最顶层,这样可以配置多个验证规则{"name":"001",//这个相当于命名空间或者id等,比如设置成url,通过url找到需验证请求是数据"validator":{"name":{//这个是需要验证的字段"validators":[//这是验证规则{"validator":"notBlank",//验证类型,这个表示不能为空"code":"1001",//自定义错误码"message":"姓名不能为空"//自定义错误提示},{"validator":"minLength","value":5},{"validator":"maxLength","value":128}]},"age":{"validators":[{"validator":"max","value":"100"},{"validator":"min","value":"10"}]},"email":{"validators":[{"validator":"email"}]},"sex":{"validators":[{"validator":"notNull"},{"validator":"inStringArray","value":["男","女","保密"]}]},"head":{"validators":[{"validator":"url"}]},"index":{"validators":[{"validator":"number"}]},"roleIds":{"validators":[{"validator":"array"}],"nodes":{//这个表示node字段是个对象属性,其还有许多属性,然后下面的配置可以无限循环嵌套"validators":[{"validator":"notNull"},{"validator":"integer"}]}},"roles":{"validators":[{"validator":"array"}],"nodes":{//这个表示node字段是个对象属性,其还有许多属性,然后下面的配置可以无限循环嵌套"name":{"validators":[{"validator":"notBlank"},{"validator":"maxLength","value":128}]}}}}},{"name":"002","validator":{}}]Java代码读取配置文件然后验证json//需要验证的json,这里简单写了,如上面示例Stringjson="{\"name\":\"\"}";//读取配置文件,初始化验证类ValidatorServicevs=newValidatorService("classpath*:/validator/*.json");//按命名去验证json内容是否合法,返回空列表则合法,非空则有不合法数据List<ValidatorResult>list=vs.validate(json,"001");目前支持验证类型[{"validator":"array"},{"validator":"boolean"},{"validator":"email"},{"validator":"equalsTo","value":"user.password"},{"validator":"inStringArray","value":["1","2","3"]},{"validator":"integer"},{"validator":"maxLength","value":"50"},{"validator":"max","value":"50.5"},{"validator":"minLength","value":"20"},{"validator":"min","value":"20.0"},{"validator":"notBlank"},{"validator":"notNull"},{"validator":"number"},{"validator":"regex","value":"","message":""},{"validator":"url"}]Maven坐标<dependency><groupId>com.onlyxiahui.framework</groupId><artifactId>only-json-validator</artifactId><version>1.0.0</version></dependency>
评论