针对 swagger 文件验证 json 有效负载 - json-schema-validator

Validating json payload against swagger file - json-schema-validator(针对 swagger 文件验证 json 有效负载 - json-schema-validator)

本文介绍了针对 swagger 文件验证 json 有效负载 - json-schema-validator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to validate a json payload against a swagger file that contains the service agreement. I am using the json-schema-validator(2.1.7) library to achieve this, but at the moment it's not validating against the specified patterns or min/max length.

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 发送,这应该验证失败,但目前返回成功:

As you can see I am sending through a correlationID of -1, which should fail validation, but at the moment is's returning as successful:

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

推荐答案

我建议使用这个库,它对我有用:

I suggest using this library, which worked for me:

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

例子:

invalid-pet.json

invalid-pet.json

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

我的 SchemaParser:

My 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);
        }
    }

这篇关于针对 swagger 文件验证 json 有效负载 - json-schema-validator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:针对 swagger 文件验证 json 有效负载 - json-schema-validator

基础教程推荐