2016-03-21 101 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試圖對語言和連載詞不可知,所以這使得它處於不可能的位置。

相關問題