自学内容网 自学内容网

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

 ​

博客主页:     南来_北往

系列专栏:Spring Boot实战


在现代软件开发中,尤其是构建 RESTful API 时,处理 JSON 数据已成为一项基本任务。JSON(JavaScript Object Notation)因其轻量级和易于人类阅读的特点,成为了数据交换的流行格式。然而,随着应用程序的复杂性增加,验证 JSON 数据以确保其符合预期的格式和结构变得至关重要。在 Spring Boot 应用中,JSON Schema 提供了一种强大且灵活的方式来校验复杂的 JSON 数据。

一、JSON Schema 简介

JSON Schema 是一种基于 JSON 的声明性规范,用于描述 JSON 数据的结构。它允许开发者定义 JSON 数据的类型、格式、必填字段、约束条件等。通过使用 JSON Schema,我们可以确保接收到的 JSON 数据符合预期的结构和格式,从而提高数据的质量和可靠性。

二、在 Spring Boot 中使用 JSON Schema

要在 Spring Boot 应用中使用 JSON Schema 来校验 JSON 数据,我们需要以下几个步骤:

1. 引入依赖

首先,我们需要在 pom.xml 文件中添加必要的依赖。通常,我们会使用 json-schema-validator 库来进行 JSON Schema 的校验。以下是一个示例依赖配置:

<dependency>  
    <groupId>com.github.fge</groupId>  
    <artifactId>json-schema-validator</artifactId>  
    <version>2.2.14</version>  
</dependency>

注意:在实际使用中,请确保使用最新版本的库。

2. 定义 JSON Schema

接下来,我们需要定义一个 JSON Schema 文件来描述我们期望的 JSON 数据结构。以下是一个简单的 JSON Schema 示例,用于校验一个包含用户名和密码的 JSON 对象:

{  
    "$schema": "http://json-schema.org/draft-07/schema#",  
    "type": "object",  
    "properties": {  
        "username": {  
            "type": "string",  
            "minLength": 5,  
            "maxLength": 20  
        },  
        "password": {  
            "type": "string",  
            "minLength": 8,  
            "maxLength": 20,  
            "pattern": "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$"  
        }  
    },  
    "required": ["username", "password"],  
    "additionalProperties": false  
}

在这个示例中,我们定义了一个包含 username 和 password 字段的 JSON 对象,并设置了相应的类型和约束条件。

3. 编写校验逻辑

在 Spring Boot 应用中,我们可以编写一个服务类来处理 JSON Schema 的校验逻辑。以下是一个示例服务类:

import com.fasterxml.jackson.databind.JsonNode;  
import com.fasterxml.jackson.databind.ObjectMapper;  
import com.github.fge.jsonschema.core.exceptions.ProcessingException;  
import com.github.fge.jsonschema.main.JsonSchema;  
import com.github.fge.jsonschema.main.JsonSchemaFactory;  
import com.github.fge.jsonschema.report.ProcessingReport;  
import org.springframework.beans.factory.annotation.Value;  
import org.springframework.core.io.ClassPathResource;  
import org.springframework.core.io.Resource;  
import org.springframework.stereotype.Service;  
  
import java.io.IOException;  
import java.nio.charset.StandardCharsets;  
import java.nio.file.Files;  
import java.nio.file.Paths;  
  
@Service  
public class JsonSchemaValidatorService {  
  
    private final JsonSchema schema;  
  
    public JsonSchemaValidatorService(@Value("${json.schema.location}") String schemaLocation) throws IOException, ProcessingException {  
        Resource resource = new ClassPathResource(schemaLocation);  
        String schemaJson = new String(Files.readAllBytes(Paths.get(resource.getURI())), StandardCharsets.UTF_8);  
        JsonSchemaFactory factory = JsonSchemaFactory.byDefault();  
        this.schema = factory.get().parse(schemaJson);  
    }  
  
    public boolean validate(JsonNode jsonNode) {  
        ProcessingReport report = schema.validate(jsonNode);  
        return report.isSuccess();  
    }  
}

在这个示例中,我们通过读取类路径下的 JSON Schema 文件来创建 JsonSchema 对象,并提供了一个 validate 方法来校验传入的 JsonNode 对象是否符合 JSON Schema。

4. 在控制器中使用校验服务

最后,我们可以在控制器中使用这个校验服务来校验接收到的 JSON 数据。以下是一个示例控制器:

import com.fasterxml.jackson.databind.JsonNode;  
import com.fasterxml.jackson.databind.ObjectMapper;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.http.HttpStatus;  
import org.springframework.http.ResponseEntity;  
import org.springframework.web.bind.annotation.*;  
  
@RestController  
@RequestMapping("/api")  
public class UserController {  
  
    @Autowired  
    private JsonSchemaValidatorService jsonSchemaValidatorService;  
  
    @PostMapping("/users")  
    public ResponseEntity<String> createUser(@RequestBody String jsonData) {  
        ObjectMapper objectMapper = new ObjectMapper();  
        try {  
            JsonNode jsonNode = objectMapper.readTree(jsonData);  
            if (jsonSchemaValidatorService.validate(jsonNode)) {  
                // 处理有效的 JSON 数据  
                return ResponseEntity.ok("User created successfully");  
            } else {  
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid JSON data");  
            }  
        } catch (IOException e) {  
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error parsing JSON data");  
        }  
    }  
}

在这个示例中,我们创建了一个 UserController,其中包含一个 createUser 方法来处理 POST 请求。该方法接收一个 JSON 字符串作为请求体,并使用 ObjectMapper 将其解析为 JsonNode 对象。然后,它调用 JsonSchemaValidatorService 的 validate 方法来校验 JSON 数据。如果校验成功,则处理有效的 JSON 数据;如果校验失败,则返回 BAD_REQUEST 状态码和错误信息。

三、总结

通过在 Spring Boot 应用中使用 JSON Schema,我们可以轻松地校验复杂的 JSON 数据,确保其符合预期的结构和格式。这不仅提高了数据的质量和可靠性,还减少了因数据格式错误而导致的错误和异常。此外,JSON Schema 的声明性特性使得它易于理解和维护,为开发人员提供了一种强大且灵活的工具来管理 JSON 数据。


原文地址:https://blog.csdn.net/2301_76419561/article/details/142866627

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!