2015-10-20 64 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],并且如果命名有变化,则会突然出现这种情况。你看到了解决办法吗? –

相关问题