oneOf
、anyOf
、allOf
是 JSON Schema 规范中用于定义复合数据结构的关键字,它们本质上是逻辑运算符在数据校验中的应用。Apifox 完全支持这些 JSON Schema 特性,帮助你构建更准确的 API 文档和数据验证规则。关键字 | 逻辑运算 | 满足条件 | 典型场景 |
---|---|---|---|
allOf | AND(与) | 必须同时满足所有条件 | 继承、扩展 |
anyOf | OR(或) | 至少满足一个条件 | 可选组合 |
oneOf | XOR(异或) | 恰好满足一个条件 | 互斥选择 |
oneOf
、anyOf
或 allOf
,为每个子模式定义具体的数据结构allOf
可以将多个数据模式组合在一起,要求数据同时满足所有条件。这就像是说 “用户信息必须包含基础信息 AND 联系方式信息”:{
"allOf": [
{
"description": "基础用户信息",
"type": "object",
"properties": {
"id": { "type": "integer" },
"name": { "type": "string" }
},
"required": ["id", "name"]
},
{
"description": "联系方式信息",
"type": "object",
"properties": {
"email": { "type": "string", "format": "email" },
"phone": { "type": "string" }
},
"required": ["email"]
}
]
}
anyOf
提供多种可选的验证路径,用户可以选择任意一种或多种方式。这就像是说 “用户可以通过用户名密码 OR 邮箱密码 OR 手机号验证码来登录”:{
"type": "object",
"properties": {
"login": {
"anyOf": [
{
"description": "用户名密码登录",
"properties": {
"username": { "type": "string" },
"password": { "type": "string" }
},
"required": ["username", "password"]
},
{
"description": "邮箱密码登录",
"properties": {
"email": { "type": "string", "format": "email" },
"password": { "type": "string" }
},
"required": ["email", "password"]
},
{
"description": "手机号验证码登录",
"properties": {
"phone": { "type": "string" },
"verifyCode": { "type": "string" }
},
"required": ["phone", "verifyCode"]
}
]
}
}
}
oneOf
确保用户只能选择一种支付方式,不允许同时提供多种。这就像是说 “支付方式必须是信用卡 XOR PayPal XOR 银行转账中的一种,且只能是一种”:{
"type": "object",
"properties": {
"payment": {
"oneOf": [
{
"description": "信用卡支付",
"type": "object",
"properties": {
"type": { "const": "credit_card" },
"cardNumber": { "type": "string" },
"expiryDate": { "type": "string" }
},
"required": ["type", "cardNumber", "expiryDate"],
"additionalProperties": false
},
{
"description": "PayPal支付",
"type": "object",
"properties": {
"type": { "const": "paypal" },
"email": { "type": "string", "format": "email" }
},
"required": ["type", "email"],
"additionalProperties": false
},
{
"description": "银行转账",
"type": "object",
"properties": {
"type": { "const": "bank_transfer" },
"accountNumber": { "type": "string" },
"routingNumber": { "type": "string" }
},
"required": ["type", "accountNumber", "routingNumber"],
"additionalProperties": false
}
]
}
}
}
allOf
(与运算)anyOf
(或运算)oneOf
(异或运算)