专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

JSON解析器之json schema校验及代码实现

项目有个业务需要对JSON格式的数据校验,需要一些必要字段的验证,实现一个JSON解析器。所以学习了json schema的语法和解析器的实现。
本篇是先说通用的JSON验证,也就是json schema和在java代码中的校验使用。

json schema是什么

json schema实际上就是一个JSON文件,文件内容是对JSON数据的结构及内容的约束,就像是xml文件的xsd文件对xml的验证。

先看一下简单的schema内容

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "这是个标题",
  "description": "校验模板内容json格式",
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "credit_card": { "type": "number" },
    "job_arr": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "billing_address": {
      "type": "object",
      "properties": {
        "selfId": {
          "type": "string"
        }
      }
    }
  },
  "dependencies": {
    "credit_card": ["billing_address"]
  },
  "required": ["name"]
}

json schema关键字

关键字 描述
$schema 表示该JSON Schema使用的版本规范,非必填,目前最新一版“Draft-07”是2019.09发布的。每个版本的语法可能有出入,方便以后人员维护建议使用
title JSON Schema文件的标题,非必填
description JSON Schema文件的描述信息,非必填
type 待校验元素的类型(例如,最外层的type表示待校验的是一个JSON对象,内层type分别表示待校验的元素类型为,number,string,array,object)
properties JSON对象中,各个key-value对中value的限制条件
required 校验的JSON对象中,必须存在的key,不存在则校验失败

typele类型常见的取值

string,object,array,integer(只能是int),number(float或者int),null,boolean

不同的type涉及的关键字(在schema文件中写上才会有作用)

  • string

maxLength: 校验string字符串的最大长度。超出长度校验失败。
minLength: 校验string字符串的最小长度。小于长度校验失败。
pattern: 字符串满足指定的正则表达式,才算通过校验。
format: 不常用,值只能是以下的取值date-time(时间格式)、email(邮件格式)、hostname(网站地址格式)、ipv4、ipv6、uri、uri-reference、uri-template、json-pointer。假如要校验的字符串是邮箱格式的可以使用”forma”t:”email”,而不用pattern自己去指定正则表达式。

  • object

properties: 每个key对应的值,都是一个json schema,则待校验JSON对象通过校验。从这里,我们可以看到,json schema的校验检测,这个对象才算是通过校验。
required: 值是个字符串数组,数组元素是本级的属性key。该关键字限制了JSON对象中必须包含哪些本级key。如果当然json不包含数组中的key则校验失败。
dependencies: 设置属性依赖,值是一个json schema。例如
“dependencies”: {”credit_card”:[”billing_address”]},
表示有字段”credit_card”就必须有”billing_address”字段。但是这个依赖是单向的。有”billing_address”字段可以没有”credit_card”。

  • array

items: 值是一个有效的JSON Schema或者一组有效的JSON Schema。只有待校验JSON数组中的所有元素均通过校验,整个数组才算通过校验。
例如:{”type”: “array”,”items”: { “type”: “string”, “minLength”: 5 }} 这个数组只有满足长度大于5才会通过校验
uniqueItems: 值是一个布尔值,即boolean(true、false)。当该关键字的值为true时,只有待校验JSON数组中的所有元素都具有唯一性时,才能通过校验。

这里只是简单的列举了一些常用的关键字,如果想要学习更多的使用方法,可以去看下官方文档里面会有更详细的用例。
json schema中文使用教程文档
json schema draft-07版本官方文档
json schema官网

在分享两个链接
根据json数据生成schema约束
使用schema约束验证json数据

在程序中实现对json数据的校验

json schema官网中java语言对json schema的实现方式有三种

  • everit-org/json-schema draft-07, -06, -04 (Apache License 2.0)
  • Justify draft-07, -06, -04 (Apache License 2.0)
  • networknt/json-schema-validator draft-07, -06, -04 Support OpenAPI 3.0 with Jackson parser (Apache License 2.0)

本篇介绍的是第三种—第三方工具feg

导入依赖fge包,因为fge的方法要用到jsonNode,所以也就需要导入jackson的包

<!-- fge -->
<dependency>  
    <groupId>com.github.fge</groupId>  
    <artifactId>json-schema-validator</artifactId>  
    <version>2.2.6</version>    
</dependency>
<!-- fasterxml -->
<dependency>  
    <groupId>com.fasterxml.jackson.core</groupId>  
    <artifactId>jackson-core</artifactId>  
    <version>2.3.0</version>    
</dependency>  
<dependency>  
    <groupId>com.fasterxml.jackson.core</groupId>  
    <artifactId>jackson-databind</artifactId>  
    <version>2.3.0</version>    
</dependency>  

将JSON数据转成jsonNode:

    /**
     * @param jsonStr 验证json字符串
     */
    private static JsonNode strToJsonNode(String jsonStr) {
        JsonNode jsonNode = null;
        try {
            jsonNode = JsonLoader.fromString(jsonStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonNode;
    }

获取本地的josn schema文件:
基于springboot项目,schema.json约束文件放在了resources/static/ 文件夹下

String jsonFilePath = “classpath:static/schema.json”;
通过spring的工具类ResourceUtils.getFile(jsonFilePath)获取到文件的绝对路径
使用classpath:方法的好处就是不用在代码中写绝对路径。部署项目时不需要关心文件的位置。只要项目中的static文件中有schema.json文件就能获取到

    /**
     * @param jsonFilePath jsonSchema文件路径
     */
    private static JsonNode schemaToJsonNode(String jsonFilePath) {
        JsonNode jsonSchemaNode=null;
        try {
            jsonSchemaNode= new JsonNodeReader().fromReader(new FileReader(ResourceUtils.getFile(jsonFilePath)));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonSchemaNode;
    }

schema校验代码实例:

    /**
     * @param jsonNode   json数据node
     * @param schemaNode jsonSchema约束node
     */
   private static boolean getProcessingReport(JsonNode jsonNode, JsonNode schemaNode) {
        //fge验证json数据是否符合json schema约束规则
        ProcessingReport report = JsonSchemaFactory.byDefault().getValidator().validateUnchecked(schemaNode, jsonNode);
        if (report.isSuccess()) {
            // 校验成功
            return true;
        } else {
            Iterator<ProcessingMessage> it = report.iterator();
                StringBuilder ms = new StringBuilder();
                ms.append("json格式错误: ");
                while (it.hasNext()) {
                    ProcessingMessage pm = it.next();
                    if (!LogLevel.WARNING.equals(pm.getLogLevel())) {
                        ms.append(pm);
                    }
                }
                System.err.println(ms);
                return false;
        }
    }

写在最后

本篇文章只为了记录和分享自己学习的成果,能够帮助更多的小伙伴当然是更好了,如果有错误欢迎指出。谢谢!

文章永久链接:https://tech.souyunku.com/27310

未经允许不得转载:搜云库技术团队 » JSON解析器之json schema校验及代码实现

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们