在jsonschema 中使用正则表达进行校验(Java)

it2024-01-16  73

json schema的基本概念这里就不多说了,有很多博客介绍地很详细,基本都是互相抄来抄去的东西。 以下是一个json schema校验所需json格式的例子。 以下是json schema的格式:

{ "$schema": "http://json-schema.org/draft-07/schema#", "$id": "http://example.com/teacher.schema.json", "title": "........", "description": ".......描述", "type": "object", "properties": { "channel_type": { "description": "......", "type": "string", "pattern": "^(hello|world|study|java)$" }, "vehicle_type": { "description": "........", "type": "string", "pattern": "^(json|schema|is|convenient)$" }, "is_need_support_camera": { "description": ".......", "type": "boolean" }, "is_use_old_roadgate": { "description": ".......", "type": "boolean" }, "is_need_remote_control_gate": { "description": ".........", "type": "boolean" }, "is_unattended": { "description": ".........", "type": "boolean" } }, "required": [ "channel_type", "vehicle_type", "is_need_support_camera", "is_use_old_roadgate", "is_need_remote_control_gate", "is_unattended" ] }

需要校验的json格式一个样例为:

{ "channel_type": "hello", "vehicle_type": "json", "is_need_support_camera":true, "is_use_old_roadgate":false, "is_need_remote_control_gate":true, "is_unattended":true }

其中channel_type和vehicle_type为string类型的字段,在这里又对他们的取值进行了限定,即channel_type只能取值为hello,world,stduy,java四个字符串中的任意一个。使用了正则表达式^(hello|world|study|java)$。进行限定。vehicle_type 字段同理。 Java 代码如下:

import com.github.fge.jsonschema.main.JsonSchema; import com.github.fge.jackson.JsonLoader; import com.github.fge.jsonschema.core.report.ProcessingReport; import com.github.fge.jsonschema.main.JsonSchemaFactory; public boolean validateJasonSchema(String validateStr, String validateSchema) { if (org.apache.commons.lang.StringUtils.isEmpty(validateStr) || org.apache.commons.lang.StringUtils .isEmpty(validateSchema)) { return false; } else { try { JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); JsonNode data = JsonLoader.fromString(validateStr); JsonNode schema = JsonLoader.fromString(validateSchema); JsonSchema jsonSchema = factory.getJsonSchema(schema); ProcessingReport report = jsonSchema.validate(data); return report.isSuccess(); } catch (Exception e) { logger.error("json schema 验证出错", e); } } return false; }

在使用相关类之前需要先在pom.xml文件中导入相关依赖,如下:

<dependency> <groupId>com.github.java-json-tools</groupId> <artifactId>json-schema-validator</artifactId> <version>2.2.10</version> </dependency>
最新回复(0)