json-schema 官方文档: https://json-schema.org/
<!-- fge -->
<dependency>
<groupId>com.github.fge</groupId>
<artifactId>json-schema-validator</artifactId>
<version>2.2.6</version>
</dependency>
<!-- fge 也可以使用下面的maven地址
<dependency>
<groupId>com.github.java-json-tools</groupId>
<artifactId>json-schema-validator</artifactId>
<version>2.2.14</version>
</dependency>
-->
/**
* json schema 校验工具类
*
* @param json 待验内容
* @param schema 格式定义
* @return 校验结果
*/
public static boolean isValidateJsonVersusSchema(String json, String schema) {
try {
ProcessingReport report = JsonSchemaFactory.byDefault().getValidator()
.validateUnchecked(OBJECT_MAPPER.readTree(schema), OBJECT_MAPPER.readTree(json));
if (report.isSuccess()) {
log.info("valid success...");
return true;
} else {
List<JsonNode> errorsJsonArray = new ArrayList<>();
for (ProcessingMessage processingMessage : report) {
errorsJsonArray.add(processingMessage.asJson());
}
log.error(errorsJsonArray.toString());
}
} catch (JsonProcessingException e) {
//jackson的异常
log.error(e.getLocalizedMessage(), e);
}
return false;
}
参考文章:https://blog.csdn.net/liuxiao723846/article/details/108578544