json-schema 官方文档: https://json-schema.org/

    1. <!-- fge -->
    2. <dependency>
    3. <groupId>com.github.fge</groupId>
    4. <artifactId>json-schema-validator</artifactId>
    5. <version>2.2.6</version>
    6. </dependency>
    7. <!-- fge 也可以使用下面的maven地址
    8. <dependency>
    9. <groupId>com.github.java-json-tools</groupId>
    10. <artifactId>json-schema-validator</artifactId>
    11. <version>2.2.14</version>
    12. </dependency>
    13. -->
    1. /**
    2. * json schema 校验工具类
    3. *
    4. * @param json 待验内容
    5. * @param schema 格式定义
    6. * @return 校验结果
    7. */
    8. public static boolean isValidateJsonVersusSchema(String json, String schema) {
    9. try {
    10. ProcessingReport report = JsonSchemaFactory.byDefault().getValidator()
    11. .validateUnchecked(OBJECT_MAPPER.readTree(schema), OBJECT_MAPPER.readTree(json));
    12. if (report.isSuccess()) {
    13. log.info("valid success...");
    14. return true;
    15. } else {
    16. List<JsonNode> errorsJsonArray = new ArrayList<>();
    17. for (ProcessingMessage processingMessage : report) {
    18. errorsJsonArray.add(processingMessage.asJson());
    19. }
    20. log.error(errorsJsonArray.toString());
    21. }
    22. } catch (JsonProcessingException e) {
    23. //jackson的异常
    24. log.error(e.getLocalizedMessage(), e);
    25. }
    26. return false;
    27. }

    参考文章:https://blog.csdn.net/liuxiao723846/article/details/108578544