"discriminator" 多态性,OpenAPI 2.0 (Swagger 2.0)

"discriminator" in polymorphism, OpenAPI 2.0 (Swagger 2.0)

引用 OpenAPI 2.0, Schema Object, or Swagger 2.0, Schema Objectdiscriminator 字段的定义为:

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.

我的困惑/问题:

目前我尝试过的:

我用来做实验的示例代码:

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 groupdiscriminatorallOf 属性 之上使用,并且在超类型中定义用于多态性。如果不使用discriminator,则allOf关键字描述一个模型包含其他模型的属性进行组合。

就像在您的示例代码中一样,Pet 是超类型,其中 petType 的 属性 标识为 discriminatorCat 是子类型Pet 的类型。以下是 Cat 对象的 json 示例:

{
  "petType": "Cat",
  "name": "‎Kitty"
}

使用discriminator意在表明属性用来标识一个对象的类型。假设有工具可以正确支持使用discriminator定义对象,则可以通过扫描属性来确定类型。比如根据petType.

识别对象是一个Cat

但是,discriminator 字段在当前版本的规范或示例中没有明确定义(请参阅 issue #403)。据我所知,Swagger目前还没有提供合适的工具支持它。

如果模型具有用于确定类型的 属性,则可以使用

discriminator。在这种情况下,它自然适合,可以作为其他开发人员了解多态关系的指标。如果考虑像 ReDoc which support discriminator (see petType in this gif and example) 这样的第三方工具,您可能会发现这很有用。

鉴别器功能在 OpenApi 3 中得到了很大改进。您现在提供一个鉴别器对象,其中包含鉴别器的名称 属性,以及 属性 到 属性 的值的映射架构名称。

(我知道你确实问过 OpenApi 2,但它在 3 中有了很大的改进,希望你能利用它)。

请参阅:https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#discriminatorObject 了解 v3.0.0 规范