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应用,如果还不会可以点击查看Spring Boot快速入门[1]
- 在
pom.xml
中添加json-schema-validator
依赖
- 创建JSON Schema
在src/main/resources
目录下创建一个validation.json
文件,然后在里面制定一套详尽的验证规则,比如下面这样:
- 创建 JsonSchema 的 Bean
当然,你也可以直接new来创建,但实战中还是推荐用Spring管理这些实例,比如 下面这样:
- 使用 JsonSchema
- 在 Web 层的应用
创建一个Controller,当接收到来自客户端的JSON数据之后,就可以像下面这样对json数据进行校验:
- 测试一下
启动 Sprint Boot 应用,然后使用你喜欢的http客户端工具对/test
接口发送测试请求:
比如,下面使用Curl来进行测试:
- 符合规则的合法请求:
校验通过,返回:[],没有错误信息
- 不符合规则的非法请求(却少order id):
校验失败,将返回错误信息:[$.order_id: is missing but it is required]
参考资料
[1]
Spring Boot快速入门: https://www.didispace.com/spring-boot-2/1-2-quick-start.html
[2]
Spring技术交流群: https://www.didispace.com/jiaqun.html
[3]
Spring Boot教程可以点击直达!: https://www.didispace.com/spring-boot-2/
[4]
What is JSON Schema?: https://json-schema.org/overview/what-is-jsonschema
[5]
JSON Schema validator: https://www.jsonschemavalidator.net/