在jsonschema中使⽤正则表达进⾏校验(Java)
json schema的基本概念这⾥就不多说了,有很多博客介绍地很详细,基本都是互相抄来抄去的东西。
以下是⼀个json schema校验所需json格式的例⼦。
以下是json schema的格式:
{
"$schema":"/draft-07/schema#",
"$id":"example/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"
时间正则表达式java},
"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.eport.ProcessingReport;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
public boolean validateJasonSchema(String validateStr, String validateSchema){
if(org.apachemons.lang.StringUtils.isEmpty(validateStr)|| org.apachemons.lang.StringUtils
.isEmpty(validateSchema)){
return false;
}else{
try{
JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
JsonNode data = JsonLoader.fromString(validateStr);
JsonNode schema = JsonLoader.fromString(validateSchema);
JsonSchema jsonSchema = JsonSchema(schema);
ProcessingReport report = jsonSchema.validate(data);
return report.isSuccess();
}catch(Exception e){
<("json schema 验证出错", e);
}
}
return false;
}
在使⽤相关类之前需要先在l⽂件中导⼊相关依赖,如下:
<dependency>
<groupId>com.github.java-json-tools</groupId>
<artifactId>json-schema-validator</artifactId>
<version>2.2.10</version>
</dependency>
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论