jsonschema networknt json-schema-validator 高级能力 自定义类校验, 自定义的key, 自定义的format取值.

 入参校验产品化 schema_个人渣记录仅为自己搜索用的博客-CSDN博客

java端jsonSchema相关

目录

每个key一个validater , 独立分析且可能会被忽略.

支持自定义的key.

官网文档自定义custom validater ,

自定义format

format能否有多个值?

  format 仅支持string

初始化 DateTimeValidator

例子

日志


每个key一个validater , 独立分析且可能会被忽略.

     所以值是long, 你也可以配置format和maxLength.

     format 内部会分析值类型, 如果不是string , 会忽略该key. 所以时间格式,配置了格式,如果传了数字会被忽略掉. 但是会被类型validater给报错, 但是设置了某个格式,就必须传long, 对于python这种来说, 无强类型, 就比较麻烦. 工具类不会自动帮你转.

    

  

    

支持自定义的key.

官网文档自定义custom validater ,

 ,需要初始化的时候设入: https://github.com/networknt/json-schema-validator/blob/master/doc/validators.md

AbstractJsonValidator 和 BaseJsonValidator ( 包含自带validator共有的函数,  要传ValidatorTypeCode.)

自定义format

format能否有多个值?

结论不能. 

  format 仅支持string

自定义的string format可以使用. 详见 

  fpe的:  addFormatValidator

 networknt:  FormatKeyword formatKeyword = new FormatKeyword(ValidatorTypeCode.FORMAT, map);
        JsonMetaSchema metaSchema = jsonSchemaVersion.getInstance()

    metaSchema.getKeywords().put(formatKeyword.getValue(), formatKeyword);

 ajv:  的 addFormat能力

借鉴自chatgpt , 谷歌了半天没答案.

Q: "networknt  JsonSchemaFactory Keyword "

A: 如下

<dependency>
            <groupId>com.networknt</groupId>
            <artifactId>json-schema-validator</artifactId>
            <version>1.0.76</version> // 2023年
        </dependency>

static String schema = "{\n"
            + "    \"$ref\": \"#/definitions/Welcome\",\n"
            + "    \"definitions\": {\n"
            + "        \"Welcome\": {\n"
            + "            \"type\": \"object\",\n"

            + "            \"additionalProperties\": false,\n"
            + "            \"properties\": {\n"
          
            + "                \"timePartition\": {\n"
            + "            \"groovy\": 131,\n"

            + "                    \"type\": \"string\""
            + "                }\n"
            + "            },\n"
            + "           
            + "            \"title\": \"Welcome\"\n"
            + "        }
            + "    }\n"
            + "}\n";

static String requestJson = "{\n"
            + "    \"timePartition\": \"2023-02-08 19:30:00\"\n"
            + "}";

自定义format的重要类AbstractFormat和format接口

相关类 FormatKeyword

FormatKeyword中new DateTimeValidator和FormatValidator, 其中 DateTimeValidator 自带, FormatValidator封装了 format , format的实现类有, 含接口用于校验.

初始化 DateTimeValidator

FormatKeyword  运行期validate时初始化DateTimeValidator

validate时,动态将format转成Validator)

例子

    protected static JsonSchema getJsonSchemaFromJsonNodeVer(JsonNode jsonNode, SpecVersion.VersionFlag versionFlag) {

        JsonSchemaVersion jsonSchemaVersion = JsonSchemaFactory.checkVersion(versionFlag);
        JsonMetaSchema metaSchema = jsonSchemaVersion.getInstance();
        GroovyKeyword value = new GroovyKeyword();
        metaSchema.getKeywords().put(value.getValue(), value);
        DateFormat dateFormat = new DateFormat();
        Map map=new HashMap<>();
        map.put(dateFormat.getName(),dateFormat);
        ;
        for (Format o : JsonSchemaVersion.BUILTIN_FORMATS) {
            map.put(o.getName(),o);

        }
        //FormatKeyword keyword = (FormatKeyword)metaSchema.getKeywords().get(ValidatorTypeCode.FORMAT.getValue());
        FormatKeyword formatKeyword = new FormatKeyword(ValidatorTypeCode.FORMAT, map);
        metaSchema.getKeywords().put(formatKeyword.getValue(), formatKeyword);
        JsonSchemaFactory factory= JsonSchemaFactory.builder().defaultMetaSchemaURI(metaSchema.getUri()).addMetaSchema(metaSchema).build();

        return factory.getSchema(jsonNode);
    }




 public static class DateFormat extends AbstractFormat {

        public DateFormat() {
            super("datetime", "(正确案例 2022-10-11 12:01:00)");
        }

        @Override
        public boolean matches(String s) {
            return s.matches("\\d{4}-\\d{1,2}-\\d{1,2} 11\\d{1,2}:\\d{1,2}:\\d{1,2}");
        }

    }

   
    public static class GroovyKeyword extends AbstractKeyword {
        private  final Logger logger = LoggerFactory.getLogger(GroovyKeyword.class);

        public GroovyKeyword() {
            super("groovy");
        }

        @Override
        public AbstractJsonValidator newValidator(String schemaPath, JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext) throws
                JsonSchemaException, Exception {
            System.out.println("GroovyKeyword_schemaPath:"+schemaPath+",schemaNodeValue:"+schemaNode+" parentSchemaNodeKv:"+ parentSchema+",validationContext="+validationContext);

            String config = schemaNode.asText();
            AbstractJsonValidator abstractJsonValidator = new AbstractJsonValidator() {
                @Override
                public Set<ValidationMessage> validate(JsonNode node, JsonNode rootNode, String at) {
                    System.out.println("GroovyKeyword.validate_config:"+config+",path:"+at+",node:"+ node);
                    System.out.println("GroovyKeyword.validate_rootNode="+rootNode);
                    return Collections.emptySet();
                }
            };
            return abstractJsonValidator;
        }
    }


日志


GroovyKeyword_schemaPath:#/definitions/Welcome/properties/timePartition

,schemaNodeValue:131 parentSchemaNodeKv:"#/definitions/Welcome/properties/timePartition" : {"groovy":131,"type":"string"},validationContext=com.networknt.schema.ValidationContext@205d38da

GroovyKeyword.validate_config:131 ,path:$.timePartition, node:"2023-02-08 19:30:00"
GroovyKeyword.validate_rootNode={"timePartition":"2023-02-08 19:30:00"}
validate_time=6

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.lsm.util; import java.text.CharacterIterator; import java.text.StringCharacterIterator; /** * 用于校验一个字符串是否是合法的JSON格式 * @author liShuMin * */ public class JsonValidator { private CharacterIterator it; private char c; private int col; public JsonValidator(){ } /** * 验证一个字符串是否是合法的JSON串 * * @param input 要验证的字符串 * @return true-合法 ,false-非法 */ public boolean validate(String input) { input = input.trim(); boolean ret = valid(input); return ret; } private boolean valid(String input) { if ("".equals(input)) return true; boolean ret = true; it = new StringCharacterIterator(input); c = it.first(); col = 1; if (!value()) { ret = error("value", 1); } else { skipWhiteSpace(); if (c != CharacterIterator.DONE) { ret = error("end", col); } } return ret; } private boolean value() { return literal("true") || literal("false") || literal("null") || string() || number() || object() || array(); } private boolean literal(String text) { CharacterIterator ci = new StringCharacterIterator(text); char t = ci.first(); if (c != t) return false; int start = col; boolean ret = true; for (t = ci.next(); t != CharacterIterator.DONE; t = ci.next()) { if (t != nextCharacter()) { ret = false; break; } } nextCharacter(); if (!ret) error("literal " + text, start); return ret; } private boolean array() { return aggregate('[', ']', false); } private boolean object() { return aggregate('{', '}', true); } private boolean aggregate(char entryCharacter, char exitCharacter, boolean prefix) { if (c != entryCharacter) return false; nextCharacter(); skipWhiteSpace(); if (c == exitCharacter) { nextCharacter(); return true; } for (;;) { if (prefix) { int start = col; if (!string()) return error("string", start); skipWhiteSpace(); if (c != ':') return error("colon", col); nextCharacter(); skipWhiteSpace(); } if (value()) { skipWhiteSpace(); if (c == ',') { nextCharacter(); } else if (c == exitCharacter) { break; } else { return error("comma or " + exitCharacter, col); } } else { return error("value", col); } skipWhiteSpace(); } nextCharacter(); return true; } private boolean number() { if (!Character.isDigit(c) && c != '-') return false; int start = col; if (c == '-') nextCharacter(); if (c == '0') { nextCharacter(); } else if (Character.isDigit(c)) { while (Character.isDigit(c)) nextCharacter(); } else { return error("number", start); } if (c == '.') { nextCharacter(); if (Character.isDigit(c)) { while (Character.isDigit(c)) nextCharacter(); } else { return error("number", start); } } if (c == 'e' || c == 'E') { nextCharacter(); if (c == '+' || c == '-') { nextCharacter(); } if (Character.isDigit(c)) { while (Character.isDigit(c)) nextCharacter(); } else { return error("number", start); } } return true; } private boolean string() { if (c != '"') return false; int start = col; boolean escaped = false; for (nextCharacter(); c != CharacterIterator.DONE; nextCharacter()) { if (!escaped && c == '\\') { escaped = true; } else if (escaped) { if (!escape()) { return false; } escaped = false; } else if (c == '"') { nextCharacter(); return true; } } return error("quoted string", start); } private boolean escape() { int start = col - 1; if (" \\\"/bfnrtu".indexOf(c) < 0) { return error("escape sequence \\\",\\\\,\\/,\\b,\\f,\\n,\\r,\\t or \\uxxxx ", start); } if (c == 'u') { if (!ishex(nextCharacter()) || !ishex(nextCharacter()) || !ishex(nextCharacter()) || !ishex(nextCharacter())) { return error("unicode escape sequence \\uxxxx ", start); } } return true; } private boolean ishex(char d) { return "0123456789abcdefABCDEF".indexOf(c) >= 0; } private char nextCharacter() { c = it.next(); ++col; return c; } private void skipWhiteSpace() { while (Character.isWhitespace(c)) { nextCharacter(); } } private boolean error(String type, int col) { System.out.printf("type: %s, col: %s%s", type, col, System.getProperty("line.separator")); return false; } public static void main(String[] args){ //String jsonStr = "{\"website\":\"oschina.net\"}"; String jsonStr = "{" + " \"ccobjtypeid\": \"1001\"," + " \"fromuser\": \"李四\"," + " \"touser\": \"张三\"," + " \"desc\": \"描述\"," + " \"subject\": \"主题\"," + " \"attach\": \"3245,3456,4345,4553\"," + " \"data\": {" + " \"desc\": \"测试对象\"," + " \"dataid\": \"22\"," + " \"billno\": \"TEST0001\"," + " \"datarelation\":[" + " {" + " \"dataname\": \"关联对象1\"," + " \"data\": [" + " {" + " \"dataid\": \"22\"," + " \"datalineid\": \"1\"," + " \"content1\": \"test1\"," + " \"content2\": \"test2\"" + " }" + " ]" + " }" + " ]" + " }" + " }"; System.out.println(jsonStr+":"+new JsonValidator().validate(jsonStr)); } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值