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

标签 json jsonschema openapi

考虑到我需要引用以下格式的 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 属性中的对象不是 ObjectA 类型,它是 ObjectB

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

有没有办法让我重用上面的 Data 架构而不创建新架构(所以这就像注入(inject) #components/schemas/ObjectA#components/schemas/ObjectB 在需要时插入数据)?

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

最佳答案

在您的简单示例中,似乎没有必要重新使用简单的 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

根据实际的复杂性,如果简单地复制共享部分,架构可能会更容易阅读/维护。

关于json - 是否可以 'inject' 引用 JSON 架构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61975987/

相关文章:

javascript - 为什么使用 JSONP 和回调而不是调用者定义的变量名?

javascript - 我的 $.getJSON 似乎没有从我的 JSON 文件中检索信息

json - 在 json 模式中,描述二进制模式的默认值、示例或枚举值的正确方法是什么?

swagger - Swagger 2.0中如何对多个参数进行分组?

swagger - 如何使用具有构造函数的开放式 api 生成器生成类模型?

python - 类型错误 : Object of type 'type' is not JSON serializable

javascript - 在 AngularJS 中获取 JSON 数组的大小

java - 无法写入 JSON 通用对象

c# - JSON 不区分大小写

python - 尝试在 Python 中制作 JSON Schema 验证器以设置默认值