第 2 课
类型、属性与必填字段
用 `type`、`properties`、`required` 与嵌套 schema 描述对象结构。
大多数日常 schema 都从对象开始。当你描述对象属性,并决定哪些字段必须出现时,JSON 对象才真正变成契约。
{
"type": "object",
"properties": {
"email": { "type": "string", "format": "email" },
"profile": {
"type": "object",
"properties": {
"displayName": { "type": "string" }
},
"required": ["displayName"]
}
},
"required": ["email", "profile"]
}
type
type 可以描述 JSON 的基础值和容器:
objectarraystringnumberintegerbooleannull
只有在不允许小数时才使用 integer。价格、坐标、比例这类可能有小数的值通常应使用 number。
properties
properties 把字段名映射到对应 schema。每个属性都可以拥有自己的类型和嵌套约束。
嵌套对象应该被明确建模。如果嵌套值有有意义的字段,就不要只写一个宽泛的 object。
required
required 是必须出现的属性名数组。一个常见误解是:写在 properties 里的字段会自动必填。事实并非如此。
这意味着你可以描述可选字段,而不强迫客户端发送它们:
{
"type": "object",
"properties": {
"title": { "type": "string" },
"subtitle": { "type": "string" }
},
"required": ["title"]
}
必填不等于非空
必填字符串仍然可以是空字符串,除非你添加 minLength。
{ "type": "string", "minLength": 1 }
把 required 理解为“存在规则”,把 minLength、minimum、pattern 这类约束理解为“值规则”。