目录 1. 什么是JSON Schema? 2. 如何定义一个JSON Schema 3. 如何测试JSON Schema a) 使用JSON Schema validator GUI b) 在Java code里使用JSON Schema validator 4.参考文档
什么是JSON Schema?
JSON模式是基于JSON格式定义JSON数据结构的规范。
JSON Data 如下
"Hello, World"
JSON Schema 定义成
{ "type": "string" }用这个Schema 我们就可以来验证JSON数据
根据Data来生成JSON Schema 有现成的工具可以用
##转载注明出处:
接下来看一个基本的JSON Schema { "$schema": "http://json-schema.org/draft-04/schema#", "title": "User", "description": "demo schema", "type": "object", "properties": { "firstName": { "type": "string" }, "LastName": { "type": "string" }, "age": { "description": "Age in years", "type": "integer", "minimum": 0 } }, "required": [ "firstName", "LastName" ] }
让我们来看看在这个模式中可以使用的各种重要的关键词:
更多的关键字可以参考
or
##转载注明出处:
如何测试JSON Schema
当我们编写了一个JSON Schema 用于对客户端提交的数据进行验证之前,我们得确保我们编写的JSON Schema是正确的,我们当然就可以构造一些数据反向验证我们的JSON Schema的正确性与否。
网上有三十多个各种语言实现的JSON Schema validator, 我们用的是Java 里非常流行的,GitHub地址在这里。
使用JSON Schema validator GUI地址
Validation results: success
Validation results: failure
Error Message的信息非常详细。
##转载注明出处:
在Java code里使用JSON Schema validator
Maven pom.xml 配置
com.fasterxml.jackson.corejackson-core2.3.0com.fasterxml.jackson.corejackson-databind2.3.0com.github.fgejson-schema-validator2.2.61 import com.fasterxml.jackson.databind.JsonNode; 2 import com.github.fge.jackson.JsonNodeReader; 3 import com.github.fge.jsonschema.core.report.ProcessingMessage; 4 import com.github.fge.jsonschema.core.report.ProcessingReport; 5 import com.github.fge.jsonschema.main.JsonSchemaFactory;
Validation success
1 @Test validate_driverSet_schema() { JsonNode schema = readJSONfile("src/test/resources/json/Schema.json"); 7 8 JsonNode data = readJSONfile("src/test/resources/json/DataGoodExample.json"); 9 10 ProcessingReport report = 11 JsonSchemaFactory.byDefault().getValidator().validateUnchecked(schema, data); 12 Assert.assertTrue(report.isSuccess()); 13 }##转载注明出处:
Validation failure
1 @Test validate_driverSet_schema2() { JsonNode data = readJSONfile("src/test/resources/json/DataBadExample.json"); 8 JsonNode schema = readJSONfile("src/test/resources/json/Schema.json"); 9 10 ProcessingReport report = 11 JsonSchemaFactory.byDefault().getValidator().validateUnchecked(schema, data); 12 Assert.assertFalse(report.isSuccess()); Iterator<ProcessingMessage> it = report.iterator(); 16 Assert.assertEquals( 17 "instance type (string) does not match any allowed primitive type (allowed: [\"integer\"])", 18 it.next().getMessage()); 19 20 } JsonNode readJSONfile(String filePath) { 23 JsonNode instance = null; 24 try { 25 instance = new JsonNodeReader().fromReader(new FileReader(filePath)); 26 } catch (FileNotFoundException e) { 27 e.printStackTrace(); 28 } catch (IOException e) { 29 e.printStackTrace(); 30 } 31 return instance; 32 }参考文档
官方文档:
GitHub:
感谢阅读,如果您觉得本文的内容对您的学习有所帮助,您可以点击右下方的推荐按钮,您的鼓励是我创作的动力。
##转载注明出处: