2016-03-21 55 views
8

的映射我需要使用Swagger为使用字符串键索引的对象映射使用(既作为输入又作为输出)的API文档。Swagger:<string,Object>

例子:

{ 
    "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”和“酒吧”可以是任何字符串键,但他们应该是一组键中是唯一的。

我知道,有扬鞭,我可以定义对象的数组,但是这给不同的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)。 我错过了什么吗?

到目前为止,我已经找到了以下变通(在扬鞭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 
       } 
      } 
     } 
    } 
} 

这几乎做工作,但读者必须明白“键”可以是任何字符串,可以重复多次。

有没有更好的方法来实现我所需要的?

+1

个人情况下,我花了一些时间了解*为什么''additionalProperties'是正确答案:http://stackoverflow.com/a/41240118/110488 –

回答

21

使用additionalProperties是使用OpenAPI(fka。Swagger)规范描述hashamp的正确方法,但Swagger UI现在不提供它们。

的问题在这里https://github.com/swagger-api/swagger-ui/issues/1248

跟踪在此期间,您可以使用这一招(在下面的例子default)同类型的地图的对象的限定非必需的财产,并给予说明内的一些提示:

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合同并改进文档。

+0

感谢您在SwaggerUI中查找相关问题的参考。不幸的是,我还没有足够的声望投票回答你的答案;-) –

+0

截至此日期,至少JavaScript版本的swagger-codegen忽略了其他属性,所以它可能是一些showstopper的一些 –

2

如果我理解正确,基本问题是Java地图没有普遍接受的JSON映射,特别是当关键字比字符串更复杂时。我已经看到GSON采用了一种方法(将键作为对象),而杰克逊则需要另一种方法(将键串化为一个字符串)。相当于一个Map(一个字典)的c#使用第三种方法(将每个条目作为一个键值对象在其自身的权利中称为“Key”和“Value”)。由于Swagger试图对语言和连载词不可知,所以这使得它处于不可能的位置。

相关问题