Json Schema 校验json,java代码示例

1、json schema 入门请参考下面两篇博客

  1.1Json Schema 快速入门

  1.2Json Schema 简介

2、java代码实现步骤

2.1引入依赖

        <!-- json schema 转换 fge -->
        <dependency>
            <groupId>com.github.fge</groupId>
            <artifactId>json-schema-validator</artifactId>
            <version>2.2.6</version>
        </dependency>

2.2创建工具类JsonSchemaUtil

import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.JsonLoader;
import com.github.fge.jackson.JsonNodeReader;
import com.github.fge.jsonschema.core.report.LogLevel;
import com.github.fge.jsonschema.core.report.ProcessingMessage;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import org.springframework.util.ResourceUtils;

import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;

public class JsonSchemaUtil {

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


    /**
     * @param jsonFilePath jsonSchema文件路径
     */
    public 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;
    }

    /**
     * @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;
        }
    }
}

2.3测试数据

schema:

{
  "$schema":"http://json-schema.org/draft-04/schema#",
  "title":"cat",
  "properties":{
    "name":{
      "type":"string"
    },
    "age":{
      "type":"number",
      "description":"Your cat's age in years"
    },
    "declawed":{
      "type":"boolean"
    },
    "description":{
      "type":"string"
    }
  },
  "required":[
    "name",
    "age",
    "declawed"
  ]
}

json:

{
    "name":"TOM",
    "age":23,
    "declawed":false,
    "description":"TOM loves to sleep all day."
}

  

参考:

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

json schema 在线测试

https://www.bbsmax.com/A/D854nv0VzE/

https://blog.csdn.net/weixin_42534940/article/details/86594376

https://www.jianshu.com/p/d94d1c87b2eb

https://blog.csdn.net/ExcellentYuXiao/article/details/52345550

原文地址:https://www.cnblogs.com/songjn/p/13361918.html