• Spring Boot 中使用 JSON Schema 来校验复杂JSON数据


     ​

    博客主页:     南来_北往

    系列专栏:Spring Boot实战


    前言

    在应用程序接口(API)的开发中,JSON作为一种数据交换格式被广泛利用。然而,对数据的结构和规则进行标准化是至关重要的,这正是JSON Schema发挥作用的地方。JSON Schema通过一套精确的关键字,能够详细地定义数据的属性,包括类型、格式及其关系等。尽管如此,如果缺乏合适的工具来执行这些标准,JSON Schema本身无法确保数据实例严格遵循所设定的模式。因此,引入JSON Schema验证器成为确保数据一致性的关键步骤。这些验证器的功能就如同一个严格的审查过程,保证每个JSON文档都严格符合模式规范。作为实现JSON Schema规范的技术手段,验证器的集成灵活性使其适用于各种规模的项目,并能够无缝整合进开发流程中,从而显著提高数据处理的效率和准确性。 

    下面我们来看看如何在Spring Boot应用中使用JSON Schema校验JSON数据 

    实践 

    要在Spring Boot中使用JSON Schema来校验复杂JSON数据,你可以使用Everit JSON Schema库。以下是如何在Spring Boot项目中集成和使用该库的步骤: 

    1、在你的pom.xml文件中添加Everit JSON Schema依赖:

    1. <dependency>
    2. <groupId>com.github.everit-org.json-schemagroupId>
    3. <artifactId>org.everit.json.schemaartifactId>
    4. <version>1.12.1version>
    5. dependency>

    2、建一个JSON Schema文件(例如user-schema.json),用于描述你的JSON数据结构:

    1. {
    2. "$schema": "http://json-schema.org/draft-07/schema#",
    3. "type": "object",
    4. "properties": {
    5. "name": {
    6. "type": "string"
    7. },
    8. "age": {
    9. "type": "integer",
    10. "minimum": 0
    11. },
    12. "email": {
    13. "type": "string",
    14. "format": "email"
    15. }
    16. },
    17. "required": ["name", "age", "email"]
    18. }

     3、在Spring Boot项目中,创建一个方法来加载JSON Schema文件并验证JSON数据:

    1. import org.everit.json.schema.Schema;
    2. import org.everit.json.schema.loader.SchemaLoader;
    3. import org.json.JSONObject;
    4. import org.json.JSONTokener;
    5. import org.springframework.stereotype.Service;
    6. import java.io.InputStream;
    7. @Service
    8. public class JsonValidationService {
    9. public boolean validateJson(String jsonData) {
    10. try {
    11. // 加载JSON Schema文件
    12. InputStream schemaStream = getClass().getResourceAsStream("/path/to/user-schema.json");
    13. JSONObject rawSchema = new JSONObject(new JSONTokener(schemaStream));
    14. Schema schema = SchemaLoader.load(rawSchema);
    15. // 将JSON数据转换为JSONObject
    16. JSONObject jsonObject = new JSONObject(jsonData);
    17. // 验证JSON数据是否符合Schema
    18. schema.validate(jsonObject);
    19. return true;
    20. } catch (Exception e) {
    21. e.printStackTrace();
    22. return false;
    23. }
    24. }
    25. }

    4、在你的控制器或其他需要验证JSON数据的地方,调用validateJson方法:

    1. import org.springframework.beans.factory.annotation.Autowired;
    2. import org.springframework.web.bind.annotation.PostMapping;
    3. import org.springframework.web.bind.annotation.RequestBody;
    4. import org.springframework.web.bind.annotation.RestController;
    5. @RestController
    6. public class UserController {
    7. @Autowired
    8. private JsonValidationService jsonValidationService;
    9. @PostMapping("/users")
    10. public String createUser(@RequestBody String userJson) {
    11. if (jsonValidationService.validateJson(userJson)) {
    12. // 保存用户数据到数据库等操作
    13. return "User created successfully";
    14. } else {
    15. return "Invalid user data";
    16. }
    17. }
    18. }

    这样,当你的应用程序接收到一个POST请求时,它会使用JSON Schema来验证请求体中的JSON数据是否符合预期的结构。如果验证失败,将返回一个错误消息。

  • 相关阅读:
    Windows下的RabbitMQ 安装
    Hive 数据模型切换后的数据验证方案
    CF1579D (1400) 贪心+优先队列
    Windows系统提权姿势
    js基础笔记学习67-对象得属性2
    支持中文繁体,支持同时配置并启用飞书和Lark认证,JumpServer堡垒机v3.10.8 LTS版本发布
    Vue3学习(二十)- 富文本插件wangeditor的使用
    Linux中输出输入重定向
    序列化和反序列化:将数据变得更加通用化
    FL Studio 21 Mac汉化免费版 附安装教程
  • 原文地址:https://blog.csdn.net/2301_76419561/article/details/140964791