在Open API中如何将一个组件定义为另一个组件的数组类型
问题根源
你之前的写法错误在于$ref指向的是student组件的properties属性节点,而非完整的student对象定义,因此Swagger渲染不符合预期。
正确实现方案
直接将数组的items指向完整的student组件即可,既复用了定义符合DRY原则,也能正常被Swagger解析:
components: schemas: student: type: object properties: StudentID: type: integer example: 3 StudentName: type: string example: David StudentRemarks: type: string example: High Grade Student students: type: array items: $ref: '#/components/schemas/student'
补充说明
- OpenAPI 3.0.x 版本不原生支持JSON Schema的
$id锚点属性,因此你添加该属性后会收到「存在额外属性」的报错,使用标准的组件引用方式即可覆盖绝大多数复用场景,无需额外定义锚点。 - 上述写法的数组项会完整继承
student组件的所有属性、示例、类型定义,和你重复写属性的渲染效果完全一致。
内容的提问来源于stack exchange,提问作者ceving
相关产品推荐
相关产品推荐

