我有一个JSON模式,我有3种类型的媒体,标题,图像和头像。
这些媒体类型中的每一种都有不同的结构,因此我使用$ref
和oneOf
指定哪些是有效的选项。
但是,我无法弄清楚如何根据兄弟姐妹的值来指定使用哪个参考。
我的模式看起来像这样
const mediaSchema = {
"type": "object",
"required": ["mediaType", "content", "points"],
"properties":{
"mediaType": {"type":"string", "pattern": "^(image|avatar|caption)$"},
"content": {
"oneOf": [
{"$ref":"#/definitions/image"},
{"$ref": "#/definitions/caption"},
{"$ref": "#/definitions/avatar"}
],
}
},
"definitions": {
"caption":
{"type": "object",
"required": ["text"],
"properties": {
"text": {"type": "string"},
"fontSize": {"type": "string", "pattern": "^[0-9]{1,3}px$"}
}
},
"image": {"type": "string", "format": "url"},
"avatar":
{"type": "object",
"properties": {
"name": {"type": "string"},
"image": {"type": "string", "format":"url"}
}
}
}
}
,当我定义像
的化身时mediaItem = {
"mediaType":"avatar",
"content": {
"name": "user name",
"avatar": "https://urlToImage
}
}
它应该有效,但是如果我将化身定义为
mediaItem = {
"mediaType": "avatar",
"content": "https://urlToImage"
}
它应该丢弃错误,因为对于媒体类型的头像无效。
您在正确的轨道上,但是您应该将单一调度器放在模式的根上,并用3个单独的常数定义"content"
作为歧视器,例如:
{
"oneOf": [
{
"type": "object",
"properties": {
"mediaType": {
"const": "avatar"
},
"content": { "$ref": "#/definitions/avatar" }
},
"required": ["mediaType", "content"]
},
// ...
],
"definitions": {
// ...
}
}
注意:"const"
关键字仅存在于JSON Schema(Draft6)的最新版本中。您使用的验证器实现可能不支持它。在这种情况下,您可以用单元枚举替换"const": "avatar"
,例如"enum": ["avatar"]