引用OpenAPI 2.0, Schema Object ,或Swagger 2.0, Schema Object ,discriminator
字段的定义为:
Adds support for polymorphism. The discriminator is the schema property name that is used to differentiate between other schema that inherit this schema. The property name used MUST be defined at this schema and it MUST be in the
required
property list. When used, the value MUST be the name of this schema or any schema that inherits it.
我的困惑/问题:
- 我不清楚它在继承或多态性中到底扮演什么角色。有人可以用一个工作示例来解释一下鉴别器,展示它到底做什么以及如果我们不使用它会怎样?有任何错误、警告或某些操作依赖于它的工具吗?
- 是这样的吗swagger-editor不支持
discriminator
,并且该字段在其他一些工具中使用?
到目前为止我已经尝试过:
- 我尝试过使用 swagger-editor以及同一文档中的示例(也在下面提到),尝试使用此属性来看看我是否可以看到它的任何特殊行为。我更改了属性,将其删除,并将
Dog
模型扩展到更深一层,并在新的子模型上尝试了相同的操作,但我在 swagger-editor 的预览中没有看到任何变化。 . - 我尝试在网上搜索,特别是stackoverflow问题,但没有找到任何相关信息。
我用来做实验的示例代码:
definitions:
Pet:
type: object
discriminator: petType
properties:
name:
type: string
petType:
type: string
required:
- name
- petType
Cat:
description: A representation of a cat
allOf:
- $ref: '#/definitions/Pet'
- type: object
properties:
huntingSkill:
type: string
description: The measured skill for hunting
default: lazy
enum:
- clueless
- lazy
- adventurous
- aggressive
required:
- huntingSkill
Dog:
description: A representation of a dog
allOf:
- $ref: '#/definitions/Pet'
- type: object
properties:
packSize:
type: integer
format: int32
description: the size of the pack the dog is from
default: 0
minimum: 0
required:
- packSize
最佳答案
根据这个google group ,discriminator
用于 allOf
属性之上,并在父类(super class)型中定义以实现多态性。如果不使用discriminator
,则allOf
关键字描述一个模型包含其他模型的属性进行组合。
就像在示例代码中一样,Pet
是一个父类(super class)型,其 petType
属性标识为 discriminator
和 Cat
是 Pet
的子类型。以下是 Cat
对象的 json 示例:
{
"petType": "Cat",
"name": "Kitty"
}
使用discriminator
旨在指示用于识别对象类型的属性。假设有工具可以通过使用鉴别器来正确支持定义对象,则可以通过扫描属性来确定类型。例如根据petType
识别出物体是Cat
。
但是,当前版本的规范或示例中没有很好地定义 discriminator
字段(请参阅 issue #403 )。据我所知,Swagger目前还没有提供合适的工具来支持它。
鉴别器
。这种情况下就自然适合了,可以作为其他开发者理解多态关系的指标。如果第三方工具如 ReDoc考虑支持 discriminator
(请参阅此 gif 和 example 中的 petType
),您可能会发现这很有用。
关于swagger - "discriminator"多态性,OpenAPI 2.0 (Swagger 2.0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39683846/