JSON Schema 入門指南【Java后端使用】


使用場景

  后端接口獲取到數據后,想看看數據是否符合我的標准,比如我想要的數據給沒給我、值是不是我需要的類型……

  當然自己的系統一般會在前端做好數據校驗,但是如果從別人的接口獲取數據呢?誰知道他們會不會按照文檔傳來標准的數據呢?

JSON Schema 作用

  寫一個json作為校驗標准,通過schema對需要校驗的json數據進行校驗。校驗數據的類型、大小、長度、……,子節點數據類型、大小、長度、……

示例

  我想要的數據需要符合以下條件:

    必須有nameagename是字符串,age是數字且只能等於10或者11sex是布爾。

  寫成json並放入/static/json/test.json中:

{
    "title" : "Match test", 
    "description" : "This is a schema that matches test-jsons.",
    "type" : "object", /*type:類型 */
    "properties" : { /*propertie:成員們的校驗條件*/
        "name" : {
            "type" : "string"       /*如果有name,它必須是字符串*/
        },
        "age" : {
                "type" : "number",      /*如果有age,它必須是數字*/
                "enum" : [10, 11]  /*enum:必須等於其中一個值 */
        },
        "sex": {
                "type" : "boolean"     /*如果有sex,它必須是布爾值*/
        }
    },
    "required": ["name", "age"] /*required:必須出現的成員*/
}

 PS  1: 可以放json文件里,也可以直接寫在Java中,只要最后能用JSONObject拿到就好

    2:注釋中的那種關鍵字有很多。可以根據想要驗證的條件,在文檔中自選關鍵字靈活運用。比如正則匹配、if-else等等

  Java中進行校驗:

    public String test()
    {
        //map轉換成json
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", "a");
        map.put("age", 10);
        JSONObject json = new JSONObject(map);//待校驗的數據
       //從文件獲取json
        InputStream test = getClass().getResourceAsStream("/static/json/test.json");
        JSONObject Schema = new JSONObject(new JSONTokener(test));//校驗標准
        Schema schema = SchemaLoader.load(Schema);
        try {
            schema.validate(json);
       System.out.println("校驗成功!");
        } catch (ValidationException e) {
            System.out.println(e.getAllMessages()); 
        }
        return "hello";
}

參考

  簡介、關鍵字、在線工具:https://www.cnblogs.com/terencezhou/p/10474617.html

  基礎關鍵字詳細:https://www.jianshu.com/p/2b7a2b1d0c49

  ※※※詳解:

    https://blog.csdn.net/swinfans/article/details/89231247?utm_medium=distribute.pc_relevant_download.none-task-blog-BlogCommendFromBaidu-1.nonecase&depth_1-utm_source=distribute.pc_relevant_download.none-task-blog-BlogCommendFromBaidu-1.nonecas

  官方Githttps://github.com/everit-org/json-schema

  官方文檔:http://json-schema.org/learn/getting-started-step-by-step.html

引入

  pom.xml中添加:

    Java6/7 versions   tomcat7可以運行

    <dependency>
        <groupId>com.github.erosb</groupId>
        <artifactId>everit-json-schema-jdk6</artifactId>
        <version>1.9.2</version>
    </dependency>
    ……
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>                                

    最新版    tomcat7報錯

    <dependency>
        <groupId>com.github.everit-org.json-schema</groupId>
        <artifactId>org.everit.json.schema</artifactId>
        <version>1.12.1</version>
    </dependency>
    ……
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>

運行

  校驗標准同上,存放在test.json文件中。文件位置 /static/json/test.json.

  Java代碼:

    Schema:自定義的校驗標准json
    json1-5:待校驗的json數據
    @PostMapping("/test")
    @ResponseBody
    public String test()
    {
        InputStream test = getClass().getResourceAsStream("/static/json/test.json");
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("name", "a");
        map1.put("age", 10);
        JSONObject json1 = new JSONObject(map1);
        
        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("name", 1);
        map2.put("age", "12");
        JSONObject json2 = new JSONObject(map2);
        
        Map<String, Object> map3 = new HashMap<String, Object>();
        map3.put("name", "a");
        map3.put("sex", "0");
        JSONObject json3 = new JSONObject(map3);
        
        Map<String, Object> map4 = new HashMap<String, Object>();
        map4.put("name", "a"); 
        map4.put("age", 11);
        map4.put("sex", 0);
        JSONObject json4 = new JSONObject(map4);
        
        Map<String, Object> map5 = new HashMap<String, Object>();
        map5.put("name", "ad");
        map5.put("age", "12");
        map4.put("sex", 0);
        JSONObject json5 = new JSONObject(map5);
        
        JSONObject Schema = new JSONObject(new JSONTokener(test));
        Schema schema = SchemaLoader.load(Schema);
        System.out.println("—————————data1———————————");
        try {
            schema.validate(json1);
            System.out.println("校驗成功!");
        } catch (ValidationException e) {
                System.out.println(e.getAllMessages()); 
        }

        System.out.println("—————————data2———————————"); 
        try {
            schema.validate(json2); 
            System.out.println("校驗成功!");
        } catch (ValidationException e) {
            System.out.println(e.getAllMessages()); 
        }
         
        System.out.println("—————————data3———————————");
        try {
            schema.validate(json3);
            System.out.println("校驗成功!");
        } catch (ValidationException e) {
                System.out.println(e.getAllMessages()); 
        }
        
        System.out.println("—————————data4———————————");
        try {
            schema.validate(json4);
            System.out.println("校驗成功!");
        } catch (ValidationException e) {
                System.out.println(e.getAllMessages()); 
        }
        
        System.out.println("—————————data5———————————");
        try {
            schema.validate(json5);
            System.out.println("校驗成功!");
        } catch (ValidationException e) {
                System.out.println(e.getAllMessages()); 
        }
        return "hello";
}

  打印結果:

—————————data1———————————
校驗成功!
—————————data2———————————
[#/name: expected type: String, found: Integer, #/age: 12 is not a valid enum value, #/age: expected type: Number, found: String]
—————————data3———————————
[#: required key [age] not found, #/sex: expected type: Boolean, found: String]
—————————data4———————————
[#/sex: expected type: Boolean, found: Integer]
—————————data5———————————
[#/age: 12 is not a valid enum value, #/age: expected type: Number, found: String]


免責聲明!

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



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