我们最早接触xml的时候会使用一个dtd文件去定义xml里可以有哪些元素和属性等,后来发展到xml schama(是一个xsd文件,在dtd的基础上提供了命名空间等更强大的功能)
现在,RESTful接口和JSON大行其道,我们可以把JSON直接存储到数据库中,提供了比原先的关系表更容易扩展的能力(虽然JSON串的存储仍然用到了关系表)。RESTful接口直接返回JSON数据,比返回xml更加简洁和易读。
xml中可以有xml schema对xml数据进行定义和校验,同样的,JSON中也有相应的叫做JSON schema的机制,来对JSON数据进行描述和定义,并且提供了相应的机制来检验某个JSON字符串是否符合JSON schema的定义。
JSON schema的语法接下来我会单独写一篇文章去总结一下,下边是一个JSON schema的简单例子,是我们的项目中用到的:
{
"$schema":"http://json-schema.org/draft-04/schema",
"type":"object",
"properties": {
"name": {
"type":"string"
},
"versions": {
"type":"array",
"items": {
"type":"object",
"properties": {
"id": {
"type":"string"
},
"version": {
"type":"integer"
},
"comment": {
"type":"string"
}
},
"required":["id", "version"],
"minItems":1
}
}
},
"required":["name", "versions"]
}
根对象是Object类型的,有两个属性,name和version 其中name是一个字符串,而version是一个数组,数组中的元素对象类型的,包括 字符串类型的id,整形的version和字符串类型的comment。
JSON scheam规定了JSON 字符串中应该有哪些元素和它们的类型是什么,也规定了哪些元素必须存在,元素的范围等等。
要检验一个给定的JSON字符串是否符合一个给定的JSON schema,在java中我们可以使用 json-schame-validator https://github.com/fge/json-schema-validator
下边是JSON schema 校验的相关代码:
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.JsonLoader;
import com.github.fge.jsonschema.core.exceptions.ProcessingException;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.main.JsonSchema;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
public class JsonShemaValidator {
private static Log log = LogFactory.getLog(JsonShemaValidator.class);
private final static JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
/**
* validate instance and Schema,here including two functions. as follows:
* first: the Draft v4 will check the syntax both of schema and instance.
* second: instance validation.
*
* @param mainSchema
* @param instance
* @return
* @throws IOException
* @throws ProcessingException
*/
public static ProcessingReport validatorSchema(String mainSchema, String instance) throws IOException, ProcessingException {
JsonNode mainNode = JsonLoader.fromString(mainSchema);
JsonNode instanceNode = JsonLoader.fromString(instance);
JsonSchema schema = factory.getJsonSchema(mainNode);
ProcessingReport processingReport = schema.validate(instanceNode);
log.info(processingReport);
return processingReport;
}
}
从返回的ProcessingReport对象中可以得到校验的结果:成功与否,以及出错信息等等
转载:https://www.cnblogs.com/jiaoyiping/p/4799754.html
JsonSchema和JsonSchemaValidator
原文:https://www.cnblogs.com/zhugongmeetyou/p/9522572.html