JSON是我们编写API时间用于数据通报的常用格式,那么你是否知道JSON Schema呢?
在数据互换范畴,JSON Schema 以其强大的标准化能力,为界说和规范 JSON 数据的结构与规则提供了有力支持。通过一系列精心设计的关键字,JSON Schema 可以或许详尽地描述数据的各项属性。然而,仅凭 JSON Schema 自己,尚不敷以验证 JSON 实例是否严酷遵循预设的模式。此时,JSON Schema 验证器的角色便显得尤为关键。这些验证器如同严酷的查抄官,确保每一个 JSON 文档都能忠实地反映出模式的界说。JSON Schema 验证器,作为实现 JSON Schema 规范的技能工具,其灵活的集成能力使得无论项目规模大小,都能轻松地将 JSON Schema 融入开发流程,从而提升数据处理的服从与准确性。
下面我们来看看如何在Spring Boot应用中使用JSON Schema校验JSON数据
动手试试
- 创建一个基本的Spring Boot应用,如果还不会可以点击检察快速入门
- 在pom.xml中添加json-schema-validator依赖
- <dependency>
- <groupId>com.networknt</groupId>
- <artifactId>json-schema-validator</artifactId>
- <version>1.4.0</version>
- </dependency>
复制代码 在src/main/resources目录下创建一个validation.json文件,然后在内里制定一套详尽的验证规则,比如下面如许:- {
- "$schema": "http://json-schema.org/draft-07/schema#",
- "title": "Order Event",
- "description": "Order event schema for example",
- "required": ["order_id", "total_price", "products" ],
- "properties": {
- "order_id": {
- "type": "string"
- },
- "event": {
- "enum": ["PLACED", "DELIVERED", "RETURNED"],
- "type": "string"
- },
- "total_price": {
- "type": "number",
- "minimum": 0
- },
- "products": {
- "type": "array",
- "items": {
- "additionalProperties": true,
- "required": ["product_id", "price"],
- "minItems": 1,
- "properties": {
- "product_id": {
- "type": "string"
- },
- "price": {
- "type": "number",
- "minimum": 0
- },
- "quantity": {
- "type": "integer"
- }
- }
- }
- }
- }
- }
复制代码 当然,你也可以直接new来创建,但实战中还是推荐用Spring管理这些实例,比如 下面如许:- @Configuration
- public class JsonSchemaConfiguration {
- private static final String SCHEMA_VALIDATION_FILE = "validation.json";
-
- @Bean
- public JsonSchema jsonSchema() {
- return JsonSchemaFactory
- .getInstance( SpecVersion.VersionFlag.V7 )
- .getSchema( getClass().getResourceAsStream( SCHEMA_VALIDATION_FILE ) );
- }
- }
复制代码- @Slf4j
- @Service
- public class JsonSchemaValidationService{
-
- @Autowired
- private JsonSchema jsonSchema;
-
- public String validateJson(JsonNode jsonNode){
-
- Set<ValidationMessage> errors = jsonSchema.validate(jsonNode);
- if(errors.isEmpty()){
- log.info("event is valid");
- }else{
- log.info("event is invalid");
- }
- return errors.toString();
- }
- }
复制代码 创建一个Controller,当吸收到来自客户端的JSON数据之后,就可以像下面如许对json数据进行校验:- import com.fasterxml.jackson.databind.JsonNode;
- @RestController
- public class JsonSchemaController {
- @Autowired
- private JsonSchemaValidationService service;
- @PostMapping("/test")
- public String validateEvent( @RequestBody JsonNode jsonNode ){
- return service.validateJson(jsonNode);
- }
- }
复制代码 启动 Sprint Boot 应用,然后使用你喜欢的http客户端工具对/test接口发送测试请求:
比如,下面使用Curl来进行测试:
- $ curl --location 'localhost:8080/test' \
- --header 'Content-Type: application/json' \
- --data '{
- "order_id":"order134",
- "event": "PLACED",
- "products": [
- {
- "product_id": "product_1",
- "price":20.5,
- "quantity":2
- }
- ],
- "total_price": 41
- }'
复制代码 校验通过,返回:[],没有错误信息
- $ curl --location 'localhost:8080/test' \
- --header 'Content-Type: application/json' \
- --data '{
- "event": "PLACED",
- "products": [
- {
- "product_id": "product_1",
- "price":20.5,
- "quantity":2
- }
- ],
- "total_price": 41
- }'
复制代码 校验失败,将返回错误信息:[$.order_id: is missing but it is required]
好了,今天的分享就到这里,希望对您有用。如果您学习过程中如遇困难?可以加入我们超高质量的Spring技能交流群,参与交流与讨论,更好的学习与进步!更多Spring Boot教程可以点击直达!,接待收藏与转发支持!
相关资料
接待关注我的公众号:程序猿DD。第一时间了解前沿行业消息、分享深度技能干货、获取优质学习资源
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |