如何在Swagger中描述含简单对象的数组模型?
在Swagger YAML中描述元素结构不固定的数组
你要描述的是元素结构不固定的对象数组(每个数组元素的属性各不相同),在Swagger(OpenAPI)的YAML模型里可以按以下两种场景处理:
场景1:允许数组元素是任意结构的对象
如果不需要限制元素的具体属性,只要求是任意键值对的对象,直接定义数组类型,并指定items为带additionalProperties: true的对象即可:
components: schemas: ArbitraryObjectArray: type: array items: type: object additionalProperties: true
如果接口直接接收这个数组作为请求体,在接口定义里引用该模型:
paths: /your-target-endpoint: post: requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/ArbitraryObjectArray'
场景2:精确限定元素的可选属性
如果需要严格匹配你给出的示例(每个元素只能包含name/class/hello其中一个必填属性),可以用oneOf来定义单个元素的结构,再组合成数组:
components: schemas: SinglePropertyObject: oneOf: - type: object required: [name] properties: name: type: string - type: object required: [class] properties: class: type: string - type: object required: [hello] properties: hello: type: string SpecificSinglePropertyArray: type: array items: $ref: '#/components/schemas/SinglePropertyObject'
这种写法会明确约束每个数组元素只能是包含指定单一属性的对象,完全匹配你提供的示例格式。
内容的提问来源于stack exchange,提问作者asim
相关产品推荐
相关产品推荐

