JSON开发笔记—— JSON Schema

导入pom

        <!-- 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>

注意:这个可能与

com.google.guava冲突
  public static void validateJsonByFgeByJsonNode(JsonNode jsonNode, JsonNode schemaNode){
        ProcessingReport report = null;
      //别有validate和validateUnchecked两种方法,区别在于validateUnchecked方法不会抛出 
       //ProcessingException异常
       report = JsonSchemaFactory.byDefault().getValidator().validateUnchecked(schemaNode, jsonNode, true);

        if (report.isSuccess()) {
            // 校验成功
            System.out.println("校验成功!");
        }else {
            System.out.println("校验失败!");
            Iterator<ProcessingMessage> it = report.iterator();
            while(it.hasNext()){
                System.out.println(it.next());
            }
        }
    }
    public static void main(String[] args) throws IOException {
        String json = "{\"checked\":\"\",\"dimensions\":{\"width\":5,\"height\":10},\"id\":1,\"name\":\"A green door\",\"price\":12.5,\"tags\":[\"home\",\"green\"]}";

        JsonNode jsonNode = JsonLoader.fromString(json);
        String chenkJson = "{\"definitions\":{},\"$schema\":\"http://json-schema.org/draft-07/schema#\",\"type\":\"object\",\"title\":\"The Root Schema\",\"required\":[\"dimensions\",\"id\",\"name\",\"price\",\"tags\"],\"properties\":{\"checked\":{\"type\":\"boolean\",\"title\":\"The Checked Schema\",\"default\":false},\"dimensions\":{\"type\":\"object\",\"title\":\"The Dimensions Schema\",\"required\":[\"width\",\"height\"],\"properties\":{\"width\":{\"type\":\"integer\",\"title\":\"The Width Schema\",\"default\":0},\"height\":{\"type\":\"integer\",\"title\":\"The Height Schema\",\"default\":0}}},\"id\":{\"type\":\"integer\",\"title\":\"The Id Schema\",\"default\":0},\"name\":{\"type\":\"string\",\"title\":\"The Name Schema\",\"default\":\"\",\"pattern\":\"^(.*)$\"},\"price\":{\"type\":\"number\",\"title\":\"The Price Schema\",\"default\":0.0},\"tags\":{\"type\":\"array\",\"title\":\"The Tags Schema\",\"items\":{\"type\":\"string\",\"title\":\"The 0 Schema\",\"default\":\"\",\"pattern\":\"^(.*)$\"}}}}";

        JsonNode chenkJsonNode = JsonLoader.fromString(chenkJson);


        validateJsonByFgeByJsonNode(jsonNode,chenkJsonNode);


    }

猜你喜欢

转载自blog.csdn.net/weixin_40403930/article/details/89333712