Validating JSON messages against Swagger definition in Java

后端 未结 2 458
逝去的感伤
逝去的感伤 2020-12-21 14:50

I created a REST API using a Swagger definition, now I need to validate incoming messages using that swagger schema. I found several solutions however all of them rely on so

2条回答
  •  旧巷少年郎
    2020-12-21 15:07

    Have a look at my answer here with a solution for this:

    Validating json payload against swagger file - json-schema-validator

    It's based on using the library: https://github.com/bjansen/swagger-schema-validator. It allows to check your json against the definitions contained in the swagger schema.

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

提交回复
热议问题