JSON Schema 入门:用 Schema 校验你的数据
JSON Schema 是一种描述 JSON 数据结构的规范。它可以定义数据类型、取值范围、必填字段等约束,实现自动化数据校验。
什么是 JSON Schema?
JSON Schema 是一个 JSON 格式的规范,用于描述其他 JSON 数据的结构和约束。
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1,
"maxLength": 50
},
"age": {
"type": "integer",
"minimum": 0,
"maximum": 150
},
"email": {
"type": "string",
"format": "email"
}
},
"required": ["name", "email"]
}
基本数据类型
JSON Schema 支持以下数据类型:
| 类型 | 说明 | 示例 |
|---|---|---|
| string | 字符串 | “hello” |
| number | 数字 | 3.14 |
| integer | 整数 | 42 |
| boolean | 布尔值 | true |
| array | 数组 | [1, 2, 3] |
| object | 对象 | {“key”: “value”} |
| null | 空值 | null |
常用约束关键字
字符串约束
{
"type": "string",
"minLength": 1,
"maxLength": 100,
"pattern": "^[a-zA-Z]+$",
"format": "email"
}
数字约束
{
"type": "number",
"minimum": 0,
"maximum": 100,
"exclusiveMinimum": 0,
"multipleOf": 0.5
}
数组约束
{
"type": "array",
"items": { "type": "string" },
"minItems": 1,
"maxItems": 10,
"uniqueItems": true
}
对象约束
{
"type": "object",
"properties": {
"name": { "type": "string" }
},
"required": ["name"],
"additionalProperties": false
}
Java 中使用 JSON Schema
import com.networknt.schema.JsonSchemaFactory;
import com.networknt.schema.JsonSchema;
import com.networknt.schema.ValidationMessage;
// 加载 Schema
JsonSchemaFactory factory = JsonSchemaFactory.getInstance();
JsonSchema schema = factory.getSchema(new FileInputStream("schema.json"));
// 校验数据
ObjectMapper mapper = new ObjectMapper();
JsonNode data = mapper.readTree(jsonString);
Set<ValidationMessage> errors = schema.validate(data);
if (errors.isEmpty()) {
System.out.println("校验通过");
} else {
errors.forEach(e -> System.out.println(e.getMessage()));
}
实战示例:用户注册 API
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"username": {
"type": "string",
"minLength": 3,
"maxLength": 20,
"pattern": "^[a-zA-Z0-9_]+$"
},
"password": {
"type": "string",
"minLength": 8,
"pattern": "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$"
},
"email": {
"type": "string",
"format": "email"
},
"phone": {
"type": "string",
"pattern": "^1[3-9]\d{9}$"
}
},
"required": ["username", "password", "email"],
"additionalProperties": false
}
JSON Schema 的优势
- 自动化校验:无需手写校验逻辑
- 文档化:Schema 本身就是数据结构的文档
- 跨语言支持:几乎所有语言都有 JSON Schema 库
- 代码生成:可以根据 Schema 自动生成代码
- Mock 数据:可以根据 Schema 生成测试数据
总结
JSON Schema 是提升 API 数据质量的利器。通过定义清晰的 Schema,可以实现自动化校验、文档生成、代码生成等多种用途。