由于传输内容以json格式传输的方式越来越多且传输入格式有时也比较复杂,在代码里添加不同的判断来验证json内容是否合法时将造成不易维护所以写了一个比较通用的内容合法性验证方法
首先在类路径下新建一个verif-xml目录在此目录下建一个xx.xml,我这里为dome.xml,内容为:
<?xml version="1.0" encoding="UTF-8"?>
<templates>
<template id="demo" memo="demo">
<field memo="类型" name="type" isNull="true" isValid="true" maxLength="5" minLength="2"/>
<field memo="状态" name="status" isNull="false" isValid="true" maxLength="5" minLength="2" maxValue="666" minValue="333" contains="1,2,3">
<precondition preName="type" preValue="null" contains="1"></precondition>
</field>
<field memo="对象" name="obj" isNull="true" isValid="true" fieldType ="obj" linkTemplateId="demoChild" maxLength="5"
minLength="2" maxValue="666" minValue="333" contains="1,2,3"/>
<field memo="金额" name="amt" isNull="false" isValid="true" maxValue="100" minValue="20"></field>
</template>
<template id="demoChild" memo="嵌套验证">
<field memo="类型" name="cType" isNull="false" isValid="true" maxLength="5" minLength="2"/>
</template>
</templates>
使用方法:
Map<String, String> verify = VerifyManager.verify("demo", json, FieldTypeEnum.FIELD_OBJ);
verify.forEach((k, v) -> {
/***说明有验证不通过的**/
System.err.println(v);
});
jar包下载 更多使用说明请见https://gitee.com/luo-hua-sheng/verify-json