是否可以 'inject' 引用 JSON 架构

Is it possible to 'inject' reference to a JSON Schema

考虑到我需要引用具有以下格式的 json:

{
    "data": {
        "type": "ObjectA"
    }
}

当我为此 json 请求编写 JSON 架构(或更具体地说,OpenAPI 规范 v3.0.3 的架构对象)时,我编写

components:
    schemas:
        Data:
            type: object
            required:
                - data
            properties:
                data:
                    $ref: '#components/schemas/ObjectA'
        ObjectA:
            type: object
            properties:
                type:
                    type: string
        ObjectB:
            type: object
            properties:
                type:
                    type: string
                some_properties:
                    type: string

... 我使用 $ref: '#components/schemas/Data'.

引用它

不过现在还有另外一个json要处理,除了data属性中的对象不是[=17]类型外,和上面那个很相似=],而是 ObjectB

{
    "data": {
        "type": "ObjectB",
        "some_properties": "which is different from ObjectA"
    }
}

有没有办法让我在不创建新模式的情况下重用上面 Data 的模式(所以这就像在需要时将 #components/schemas/ObjectA#components/schemas/ObjectB 注入数据)?

我考虑过使用 oneOf 但它不适合,因为只有特定对象对特定 API 端点有效(即使所有对象都在数据 属性 下)任何一个可用对象。

在您的简单示例中,似乎没有必要重新使用简单的 Data 定义。但是,假设您的实际结构更复杂,您可以通过 allOf 将一般属性与特定属性结合起来,例如

components:
    schemas:
        BaseData:
            type: object
            required:
                - data
            properties:
                data:
                    type: object
                    properties:
                        type:
                            type: string
                    required:
                        - type
        DataA:
            allOf:
                - $ref: '#components/schemas/BaseData'
                - type: object
                  properties: 
                      data:
                          $ref: '#components/schemas/ObjectA'
        DataB:
            allOf:
                - $ref: '#components/schemas/BaseData'
                - type: object
                  properties: 
                      data:
                          $ref: '#components/schemas/ObjectB'
        ObjectA:
            type: object
            properties:
                type:
                    const: ObjectA
        ObjectB:
            type: object
            properties:
                type:
                    const: ObjectB
                some_properties:
                    type: string
                required:
                    - some_properties

根据实际的复杂性,如果只是复制共享部分,架构可能更容易 read/maintain。