【发布时间】:2016-07-08 07:22:01
【问题描述】:
我需要使用 Swagger 记录一个 API,该 API 使用对象映射作为输入和输出,由字符串键索引。
例子:
{
"a_property": {
"foo": {
"property_1": "a string 1",
"property_2": "a string 2"
},
"bar": {
"property_1": "a string 3",
"property_2": "a string 4"
}
}
}
"foo" 和 "bar" 可以是任何字符串键,但它们在键集中应该是唯一的。
我知道,使用 Swagger,我可以定义一个对象数组,但这提供了不同的 API,因为我们将拥有如下内容:
{
"a_property": [
{
"key": "foo"
"property_1": "a string 1",
"property_2": "a string 2"
},
{
"key": "bar"
"property_1": "a string 3",
"property_2": "a string 4"
}
]
}
我已阅读'Open API Specification' - 'Add support for Map data types #38' 页面。据我了解,它建议使用 additionalProperties,但它似乎无法满足我的需求(或者它不适用于我使用的 Swagger UI 2.1.4)。 我错过了什么吗?
到目前为止,我已经找到了以下解决方法(在 Swagger JSON 中):
a_property: {
description: "This is a map that can contain several objects indexed by different keys.",
type: object,
properties: {
key: {
description: "map item",
type: "object",
properties: {
property_1: {
description: "first property",
type: string
},
property_2: {
description: "second property",
type: string
}
}
}
}
}
这几乎可以完成这项工作,但读者必须了解“key”可以是任何字符串,并且可以重复多次。
有没有更好的方法来实现我的需要?
【问题讨论】:
-
我个人花了一些时间才明白为什么
additionalProperties是正确答案:stackoverflow.com/a/41240118/110488
标签: dictionary swagger openapi