引入依赖

    1. <!--json schema end-->
    2. <dependency>
    3. <groupId>com.github.fge</groupId>
    4. <artifactId>json-schema-validator</artifactId>
    5. <version>2.2.6</version>
    6. </dependency>

    创建工具类JsonSchemaUtils

    1. /**
    2. * JsonSchema工具类
    3. */
    4. public class JsonSchemaUtils {
    5. /**
    6. * 从指定路径读取Schema信息
    7. *
    8. * @param filePath Schema路径
    9. * @return JsonNode型Schema
    10. * @throws IOException 抛出IO异常
    11. */
    12. private static JsonNode readJSONfile(String filePath) throws IOException {
    13. InputStream stream = JsonSchemaUtils.class.getClassLoader().getResourceAsStream(filePath);
    14. return new JsonNodeReader().fromInputStream(stream);
    15. }
    16. /**
    17. * 将Json的String型转JsonNode类型
    18. *
    19. * @param str 需要转换的Json String对象
    20. * @return 转换JsonNode对象
    21. * @throws IOException 抛出IO异常
    22. */
    23. private static JsonNode readJSONStr(String str) throws IOException {
    24. return new ObjectMapper().readTree(str);
    25. }
    26. /**
    27. * 将需要验证的JsonNode 与 JsonSchema标准对象 进行比较
    28. *
    29. * @param schema schema标准对象
    30. * @param data 需要比对的Schema对象
    31. */
    32. private static void assertJsonSchema(JsonNode schema, JsonNode data) {
    33. ProcessingReport report = JsonSchemaFactory.byDefault().getValidator().validateUnchecked(schema, data);
    34. if (!report.isSuccess()) {
    35. for (ProcessingMessage aReport : report) {
    36. Reporter.log(aReport.getMessage(), true);
    37. }
    38. }
    39. Assert.assertTrue(report.isSuccess());
    40. }
    41. /**
    42. * 将需要验证的response 与 JsonSchema标准对象 进行比较
    43. *
    44. * @param schemaPath JsonSchema标准的路径
    45. * @param response 需要验证的response
    46. * @throws IOException 抛出IO异常
    47. */
    48. public static void assertResponseJsonSchema(String schemaPath, String response) throws IOException {
    49. JsonNode jsonSchema = readJSONfile(schemaPath);
    50. JsonNode responseJN = readJSONStr(response);
    51. assertJsonSchema(jsonSchema, responseJN);
    52. }
    53. }

    使用校验

    1. JsonSchemaUtils.assertResponseJsonSchema(SCHEMA_PATH, JSONObject.toJSONString(body));