2015-10-20 21 views
2

我有一個API,我發佈了一組對象到服務器,按類型區分,其中每個類型都有一些不同的參數。這些命令結構如下所示:如何指定對象的類型是幾種可能的對象類型之一?

{ 
    "type": <command-name>, 
    "args": { 
     <command-specific args> 
    } 
} 

例如,這些可能是兩種可能的命令:

{ 
    "type": "Flooblinate", 
    "args": { 
     "intensity": "High", 
     "frequency": "Every blue moon" 
    } 
} 

{ 
    "type": "Blagostrate", 
    "args": { 
     "temperature": 34.5, 
     "darkMatter": true 
    } 
} 

我怎樣才能在揚鞭指定此?我可以指定enum"type",但我怎麼說「"args"是這些可能的對象之一」?

我已經簽出the docs但沒有什麼突出的。最有前途的一個是allOf,因爲它在編輯器中顯示的很好(pastebin,粘貼到online editor):

definitions: 
    Product: 
    type: object 
    allOf: 
    - type: object 
     title: Flooblinate 
     properties: 
     intensity: 
      type: string 
     frequency: 
      type: string 

    - type: object 
     title: Blagostrate 
     properties: 
     temperature: 
      type: number 
     darkMatter: 
      type: boolean 

,看起來像這樣:

enter image description here

然而,這不是語義我所需要的,並且毫不奇怪,在online viewer(那個沒有爲我的測試案例設置,不知道如何很容易地連接本地文件的情況下),它們被呈現爲好像所有的字段同時出現,當然是什麼allOf mea NS:

enter image description here

做什麼用揚鞭代表這個正確的方法是什麼?

回答

1

據羅恩the google group輸入,我要的是使用discriminator屬性:

definitions: 
    Product: 
    type: object 
    discriminator: type 
    properties: 
     type: string 
    required: [type] 
    Flooblinate: 
    allOf: 
    - $ref: '#/definitions/Product' 
    - type: object 
     properties: 
     intensity: 
      type: string 
     frequency: 
      type: string 
    Blagostrate: 
    allOf: 
    - $ref: '#/definitions/Product' 
    - type: object 
     properties: 
     temperature: 
      type: number 
     darkMatter: 
      type: boolean 

語義,這意味着我想它的意思。無論API接受還是返回FlooblinateBlagostrate中的任何一個,我都應指定$ref: '#/definitions/Product'。請注意,這需要對象上的字段(此處稱爲type)充當鑑別器。

我認爲這可能是方法,但工具沒有顯示我的預期。但是:

這是因爲工具不是100%支持鑑別器 - 但是,這是描述您的用例的正確方法。 一旦你在頂層模型中定義了鑑別器,任何'allOf'都將被認爲是一個可行的選項,而且你確實參考了頂級模型的使用。

+0

我在這裏看到的問題是鑑別器:類型必須匹配每個產品子對象的名稱。您需要讓產品擁有一個「類型」字段,其中的值與子對象的名稱緊密結合[Flooblinate,Blagostrate],並且如果命名有變化,則會突然出現這種情況。你看到了解決辦法嗎? –

相關問題