我正在尝试使用 Swagger 来描述我正在构建的 web-api。问题是我无法理解如何描述复杂的 json 对象?
例如,如何描述这个对象:
{
name: "Jhon",
address: [
{
type: "home",
line1: "1st street"
},
{
type: "office",
line1: "2nd street"
}
]
}
我正在尝试使用 Swagger 来描述我正在构建的 web-api。问题是我无法理解如何描述复杂的 json 对象?
例如,如何描述这个对象:
{
name: "Jhon",
address: [
{
type: "home",
line1: "1st street"
},
{
type: "office",
line1: "2nd street"
}
]
}
好的,根据上面的评论,您需要以下架构:
{
"definitions": {
"user": {
"type": "object",
"required": [ "name" ],
"properties": {
"name": {
"type": "string"
},
"address": {
"type": "array",
"items": {
"$ref": "#/definitions/address"
}
}
}
},
"address": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": [ "home", "office" ]
},
"line1": {
"type": "string"
}
}
}
}
}
我做了一些假设,以使示例更复杂一些,以在将来提供帮助。对于“用户”对象,我已经声明“名称”字段是强制性的。例如,如果您还需要地址是强制性的,您可以将定义更改为“必需”:[“名称”,“地址”]。
我们基本上使用 json-schema 的一个子集来描述模型。当然不是每个人都知道它,但它的学习和使用相当简单。
对于您可以看到的地址类型,我还将限制设置为两个选项 - 家庭或办公室。您可以向该列表添加任何内容,或完全删除“枚举”以删除该约束。
当属性的“类型”为“数组”时,您需要将其与“项目”一起声明数组的内部类型。在这种情况下,我引用了另一个定义,但该定义也可能是内联的。以这种方式维护通常更容易,特别是如果您需要单独或在其他模型中的“地址”定义。
根据要求,内联版本:
{
"definitions": {
"user": {
"type": "object",
"required": [
"name"
],
"properties": {
"name": {
"type": "string"
},
"address": {
"type": "array",
"items": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": [
"home",
"office"
]
},
"line1": {
"type": "string"
}
}
}
}
}
}
}
}