【问题标题】:Validating json payload against swagger file - json-schema-validator针对 swagger 文件验证 json 有效负载 - json-schema-validator
【发布时间】:2019-04-21 19:45:39
【问题描述】:

我正在尝试针对包含服务协议的 swagger 文件验证 json 有效负载。我正在使用 json-schema-validator(2.1.7) 库来实现这一点,但目前它没有针对指定的模式或最小/最大长度进行验证。

Java 代码:

public void validateJsonData(final String jsonData) throws IOException, ProcessingException {

    ClassLoader classLoader = getClass().getClassLoader();
    File jsonSchemaFile = new File (classLoader.getResource("coachingStatusUpdate.json").getFile());

    String jsonSchema = new String(Files.readAllBytes(jsonSchemaFile.toPath()));

    final JsonNode dataNode = JsonLoader.fromString(jsonData);
    final JsonNode schemaNode = JsonLoader.fromString(jsonSchema);

    final JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
    JsonValidator jsonValidator = factory.getValidator();

    ProcessingReport report = jsonValidator.validate(schemaNode, dataNode);
    System.out.println(report);
    if (!report.toString().contains("success")) {
        throw new ProcessingException (
                report.toString());
    }
}

我发送的消息

{
  "a": "b",
  "c": "d",
  "e": -1,
  "f": "2018-10-30",
  "g": "string" }

招摇定义:

    {
  "swagger": "2.0",
  "info": {
    "version": "1.0.0",
    "title": "Test",
    "termsOfService": "http://www.test.co.za",
    "license": {
      "name": "Test"
    }
  },
  "host": "localhost:9001",
  "basePath": "/test/",
  "tags": [
    {
      "name": "controller",
      "description": "Submission"
    }
  ],
  "paths": {
    "/a": {
      "put": {
        "tags": [
          "controller"
        ],
        "summary": "a",
        "operationId": "aPUT",
        "consumes": [
          "application/json;charset=UTF-8"
        ],
        "produces": [
          "application/json;charset=UTF-8"
        ],
        "parameters": [
          {
            "in": "body",
            "name": "aRequest",
            "description": "aRequest",
            "required": true,
            "schema": {
              "$ref": "#/definitions/aRequest"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Received",
            "schema": {
              "$ref": "#/definitions/a"
            }
          },
          "400": {
            "description": "Bad Request"
          },
          "401": {
            "description": "Unauthorized"
          },
          "408": {
            "description": "Request Timeout"
          },
          "500": {
            "description": "Generic Error"
          },
          "502": {
            "description": "Bad Gateway"
          },
          "503": {
            "description": "Service Unavailable"
          }
        }
      }
    }
  },
  "definitions": {
    "aRequest": {
      "type": "object",
      "required": [
        "a",
        "b",
        "c",
        "d"
      ],
      "properties": {
        "a": {
          "type": "string",
          "description": "Status",
          "enum": [
            "a",
            "b",
            "c",
            "d",
            "e",
            "f",
            "g",
            "h"
          ]
        },
        "aReason": {
          "type": "string",
          "description": "Reason",
          "enum": [
            "a",
            "b",
            "c",
            "d",
            "e",
            "f",
            "g",
            "h",
            "i",
            "j",
            "k",
            "l",
            "m",
            "n"
          ]
        },
        "correlationID": {
          "type": "integer",
          "format": "int32",
          "description": "",
          "minimum": 1,
          "maximum": 9999999
        },
        "effectiveDate": {
          "type": "string",
          "format": "date",
          "description": ""
        },
        "f": {
          "type": "string",
          "description": "",
          "minLength": 1,
          "maxLength": 100
        }
      }
    },
    "ResponseEntity": {
      "type": "object",
      "properties": {
        "body": {
          "type": "object"
        },
        "statusCode": {
          "type": "string",
          "enum": [
            "100",
            "101",
            "102",
            "103",
            "200",
            "201",
            "202",
            "203",
            "204",
            "205",
            "206",
            "207",
            "208",
            "226",
            "300",
            "301",
            "302",
            "303",
            "304",
            "305",
            "307",
            "308",
            "400",
            "401",
            "402",
            "403",
            "404",
            "405",
            "406",
            "407",
            "408",
            "409",
            "410",
            "411",
            "412",
            "413",
            "414",
            "415",
            "416",
            "417",
            "418",
            "419",
            "420",
            "421",
            "422",
            "423",
            "424",
            "426",
            "428",
            "429",
            "431",
            "451",
            "500",
            "501",
            "502",
            "503",
            "504",
            "505",
            "506",
            "507",
            "508",
            "509",
            "510",
            "511"
          ]
        },
        "statusCodeValue": {
          "type": "integer",
          "format": "int32"
        }
      }
    }
  }
}

如您所见,我通过 -1 的相关 ID 发送,这应该验证失败,但目前返回成功:

com.github.fge.jsonschema.report.ListProcessingReport: success

【问题讨论】:

  • 你能发布整个架构吗?
  • @slimane 我添加了整个架构
  • 你确定这个 json-schema-validator 支持 OpenAPI/Swagger 模式吗? OpenAPI 格式不同于普通的 JSON Schema。
  • @Helen 我不确定,我找不到任何其他可以验证架构文件的组件

标签: java json swagger jsonschema json-schema-validator


【解决方案1】:

json-schema-validator 似乎只适用于纯 JSON 模式。 OpenAPI 规范使用 JSON Schema 的扩展子集,因此模式格式不同。您需要一个可以专门针对 OpenAPI/Swagger 定义进行验证的库,例如 Atlassian 的 swagger-request-validator

【讨论】:

  • swagger-request-validator 有替代品吗?他们似乎没有回应未解决的问题……
  • @HaroldL.Brown 我不知道有任何其他 Java 库。
  • @HaroldL.Brown 有什么具体问题吗?该项目处于活跃状态,并定期解决和响应问题。
  • @SvenDöring 我对 Atlassian 的响应能力并不强,而且项目中有很多错误,使其几乎无法使用。
  • swagger-request-validator 是否有点网核心实现?
【解决方案2】:

我建议使用这个对我有用的库:

https://github.com/bjansen/swagger-schema-validator

例子:

invalid-pet.json

{
  "id": 0,
  "category": {
    "id": 0,
    "name": "string"
  },
  "named": "doggie",
  "photoUrls": [
    "string"
  ],
  "tags": [
    {
      "id": 0,
      "name": "string"
    }
  ],
  "status": "available"
}

我的 SchemaParser:

@Component
public class SchemaParser {

    private Logger logger = LoggerFactory.getLogger(getClass());

    public boolean isValid(String message, Resource schemaLocation) {

        try (InputStream inputStream = schemaLocation.getInputStream()) {
            SwaggerValidator validator = SwaggerValidator.forJsonSchema(new InputStreamReader(inputStream));
            ProcessingReport report = validator.validate(message, "/definitions/Pet");
            return report.isSuccess();
        } catch (IOException e) {
            logger.error("IOException", e);
            return false;
        } catch (ProcessingException e) {
            e.printStackTrace();
            return false;
        }
    }
}

测试:

    @Test
    void shouldFailValidateWithPetstoreSchema() throws IOException {

        final Resource validPetJson = drl.getResource("http://petstore.swagger.io/v2/swagger.json");

        try (Reader reader = new InputStreamReader(validPetJson.getInputStream(), UTF_8)) {
            final String petJson = FileCopyUtils.copyToString(reader);
            final boolean valid = schemaParser.isValid(petJson, petstoreSchemaResource);
            assertFalse(valid);
        }
    }

【讨论】:

  • 你能告诉我可以在哪个包中找到 SwaggerValidator 吗?
  • 我可以看到这些包 import com.atlassian.oai.validator.SwaggerRequestResponseValidator;导入 com.atlassian.oai.validator.schema.SchemaValidator;导入 com.github.fge.jsonschema.core.report.ProcessingReport;导入 io.swagger.validate.SwaggerJsonValidator;但不是 SwaggerValidator
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-21
  • 2018-05-24
  • 2020-04-30
  • 2017-01-09
  • 1970-01-01
  • 2020-12-01
  • 2021-11-04
相关资源
最近更新 更多