zoukankan      html  css  js  c++  java
  • Java使用JsonSchema实例,基于Springboot

    先自定义一个json数据格式标准,放在一个json文件中,json文件放在resources下面

    {
      "title" : "标题",
      "description" : "描述",
      "type" : "object",
      "properties" : {
        "name" : {
          "type" : "string"
        },
        "age" : {
          "type" : "number",
          "enum" : [10, 11]
        },
        "sex": {
          "type" : "boolean"
        }
      },
      "required": ["name", "age"]
    }
    

    再定义一个json数据,用于传入校验,同样放在resources下面

    {
      "name": "a",
      "age": 10
    }
    

    加载出两个json文件,进行校验

    
    import org.everit.json.schema.Schema;
    import org.everit.json.schema.loader.SchemaLoader;
    import org.json.JSONObject;
    import org.json.JSONTokener;
    import org.junit.Test;
    
    import java.io.InputStream;
    
    
    public class TestJson {
    
        @Test
        public void TestJson() {
    
    //        得到待校验的json数据
            InputStream inputStreamjson = getClass().getResourceAsStream("/getjson.json");
            JSONObject jsonObjectjson = new JSONObject(new JSONTokener(inputStreamjson));
            System.out.println("待校验的json数据:" + jsonObjectjson);
    
    
    //        得到设定的标准json
            InputStream inputStreamjsonSchema = getClass().getResourceAsStream("/one.json");
            JSONObject jsonObjectSchema = new JSONObject(new JSONTokener(inputStreamjsonSchema));
            System.out.println("标准格式:"+jsonObjectSchema);
    
    //        Schema对象加载设定的标准json
            Schema schema = SchemaLoader.load(jsonObjectSchema);
    //        对得到的json数据进行校验
            schema.validate(jsonObjectjson);
    
    
        }
    
    
    }
    
    

    测试

    当age为8时,测试不通过

    当age为10时,测试通过

  • 相关阅读:
    索引yellow 分片 UNASSIGNED 解决方案1
    Linux zip压缩多文件
    查询数据库实例名,服务名,和oracle_sid
    excel2csv 多sheet拆分到不同csv
    创建按月自动分区表
    自动生成sequence
    oracle 11g 分区表创建(自动按年、月、日分区)
    linux 查找字符串
    Oracle 字符串截取和位置
    mongodb查询某个字段数据
  • 原文地址:https://www.cnblogs.com/lyd447113735/p/14836649.html
Copyright © 2011-2022 走看看