【问题标题】:Validation of JSON Schema in JavaJava 中 JSON Schema 的验证
【发布时间】:2020-10-28 08:26:50
【问题描述】:

我在 2019 年 9 月 (https://json-schema.org/draft/2019-09/release-notes.html) 之前编写了一个 JSON 模式。如何使用 java 进行验证?

我要写方法(验证失败抛出异常):

void validate(Path pathToSchema) throws Exception {
   // validation of schema by pathToSchema
}

附:我想验证 JSON Schema 的正确性,而不是 JSON Schema 的 JSON Document。

【问题讨论】:

标签: java json jsonschema


【解决方案1】:

你用众所周知的networknt lib做这样的事情:

    JsonSchema schema = null;
    JsonSchemaFactory factory = JsonSchemaFactory.getInstance(VersionFlag.V201909);
    try {
      schema = factory.getSchema(
          "{\n"
              + "  \"$schema\": \"http://json-schema.org/draft/2019-09/schema\",\n"
              + "  \"$id\": \"#MyJsonClassSchema.json\",\n"
              + "  \"type\": \"object\",\n"
              + "  \"properties\": {\n"
              + "    \"myProperty\": {\n"
              + "      \"type\": \"string\"\n"
              + "    }\n"
              + "  }\n"
              + "}"
      );
    } catch (JsonSchemaException e) {
      System.out.println("json schema invalid: \n" + e);
    }
    return schema;

这将从您在输入中设置的架构版本开始验证 json 架构的某些功能。

【讨论】:

    【解决方案2】:

    您可以使用 Json 验证器:-https://github.com/fge/json-schema-validator

    或者您可以简单地尝试使用 Google Gson 解析 Json 并捕获语法异常以验证它,如下所示:-

    try{
    JsonParser parser = new JsonParser();
    parser.parse(passed_json_string);
    } 
    catch(JsonSyntaxException jse){
    System.out.println("Not a valid Json String:"+jse.getMessage());
    }
    

    【讨论】:

    • 我想验证模式,而不是按模式记录。
    • 这行不通,因为你提到的实现不支持草案 2019-09
    猜你喜欢
    • 1970-01-01
    • 2021-04-18
    • 2019-10-18
    • 2015-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多