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

各種類型示例


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM