不可错过的JSON验证神器JSON Schema Validator
1.什么是JSON Schema Validator?
json-schema-validator 是一个用于验证 JSON 数据结构的 Java 库。它基于 JSON Schema 标准,允许开发人员定义 JSON 数据的结构、格式和约束条件,并在应用程序中验证 JSON 数据是否符合这些定义。该库由 com.github.fge 提供,是处理 JSON 数据验证的强大工具。
2.原理
json-schema-validator 的核心原理是使用 JSON Schema 描述 JSON 数据的预期结构和约束。JSON Schema 是一种类似于 XML Schema 的描述语言,允许开发人员定义 JSON 数据的类型、格式、必需字段、默认值等。json-schema-validator 通过解析 JSON Schema,并将其应用于待验证的 JSON 数据,检查数据是否符合定义的结构和约束。
3.使用场景
- 数据验证:在接收外部 JSON 数据时,确保数据格式和内容符合预期,避免数据不一致或错误。
- API 开发:在 RESTful API 中,验证请求和响应的 JSON 数据结构,确保 API 的稳定性和一致性。
- 配置文件验证:验证应用程序配置文件的格式和内容,确保配置的正确性。
4.代码工程
实验目标
使用 json-schema-validator 验证 JSON 数据
依赖配置
首先,在你的 pom.xml 中添加 json-schema-validator 依赖:
springboot-demo
com.et
1.0-SNAPSHOT
4.0.0
JSON-Schema-Validator
8
8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-autoconfigure
org.springframework.boot
spring-boot-starter-test
test
com.github.fge
json-schema-validator
2.2.6
JSON Schema
定义一个简单的 JSON Schema,用于描述用户对象:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"age": {
"type": "integer",
"minimum": 0
},
"email": {
"type": "string",
"format": "email"
}
},
"required": ["name", "email"]
}
service
使用 json-schema-validator 验证 JSON 数据:
package com.et.services;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.fge.jackson.JsonLoader;
import com.github.fge.jsonschema.core.exceptions.ProcessingException;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.main.JsonSchema;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import java.io.IOException;
@Service
public class JsonSchemaValidatorService {
private final JsonSchema schema;
public JsonSchemaValidatorService() throws IOException, ProcessingException {
JsonNode schemaNode = JsonLoader.fromResource("/schemas/user-schema.json");
JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
this.schema = factory.getJsonSchema(schemaNode);
}
public ProcessingReport validate(String jsonData) throws IOException, ProcessingException {
ObjectMapper mapper = new ObjectMapper();
JsonNode dataNode = mapper.readTree(jsonData);
return schema.validate(dataNode);
}
}
controller
package com.et.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class HelloWorldController {
@RequestMapping("/hello")
public Map showHelloWorld(){
Map map = new HashMap<>();
map.put("msg", "HelloWorld");
return map;
}
}
以上只是一些关键代码,所有代码请参见下面代码仓库
代码仓库
- https://github.com/Harries/springboot-demo(JSON-Schema-Validator)
5.测试
- 启动Spring Boot应用
- postman 请求http://localhost:8088/api/users
6.引用
- https://json-schema.org/