昂首阔步:< string,Object>的映射; [英] Swagger: map of <string, Object>
问题描述
我需要用Swagger记录一个API,该API既使用输入图又使用输出由字符串键索引的对象图.
I need to document with Swagger an API that uses, both as input and output, maps of objects, indexed by string keys.
示例:
{
"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"可以是任何字符串键,但是它们在键集中应该是唯一的.
"foo" and "bar" can be any string keys, but they should be unique among the set of keys.
我知道,使用Swagger,我可以定义一个对象数组,但这提供了不同的API,因为那时我们将得到以下内容:
I know that, with Swagger, I can define an array of objects, but this gives a different API since we then would have something as:
{
"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规范"-添加对Map数据类型的支持# 38'页.据我了解,它建议使用 additionalProperties,但似乎不能满足我的需求(或者它不适用于我使用的Swagger UI 2.1.4). 我错过了什么吗?
I have read the 'Open API Specification' - 'Add support for Map data types #38' page. As far as I understand, it recommends to use additionalProperties, but it doesn't seem to answer my need (or it doesn't work with Swagger UI 2.1.4 that I use). Did I miss something?
到目前为止,我已经找到以下解决方法(在Swagger JSON中):
So far I have found the following work-around (in 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
}
}
}
}
}
这几乎可以完成工作,但是读者必须了解键"可以是任何字符串,并且可以重复多次.
This almost does the job, but the reader has to understand that "key" can be any string, and can be repeated several times.
是否有更好的方法来满足我的需求?
推荐答案
使用additionalProperties
是使用OpenAPI(fka.Swagger)规范描述hashamp的正确方法,但是Swagger UI目前暂不呈现它们.
Using additionalProperties
is the proper way to describe hashamp with OpenAPI (fka. Swagger) Specification but Swagger UI do not render them for now.
在此跟踪问题 https://github.com/swagger-api /swagger-ui/issues/1248
与此同时,您可以使用此技巧定义与地图对象类型相同的非必需属性(在下面的示例中为default
),并在说明中提供一些提示:
In the meanwhile you can use this trick define a non required property (default
in the example below) of the same type of the map's objects and give some hint within the description:
swagger: "2.0"
info:
version: 1.0.0
title: Hashmap
paths: {}
definitions:
MapItem:
properties:
firstname:
type: string
lastname:
type: string
Map:
description: a (key, MapItem) map. `default`is an example key
properties:
default:
$ref: '#/definitions/MapItem'
additionalProperties:
$ref: '#/definitions/MapItem'
此描述不会修改API合同并不会改善文档.
This description do not modify API contract and improve documentation.
这篇关于昂首阔步:< string,Object>的映射;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!