如何在OpenAPI中定义含2个不同枚举项的固定3元素字符串数组?
解决方法
你之前的写法逻辑有误——把allOf放在items下面,意味着每个数组元素都要同时满足三个schema,但一个字符串不可能既是option A/B又是option C/D,工具只能把两个枚举合并后让你选一个,完全不符合需求。
要实现“恰好3个元素,分别来自两个枚举和一个普通字符串(顺序不限)”,可以用contains结合数组长度约束:
filters: type: array minItems: 3 maxItems: 3 uniqueItems: true allOf: - contains: title: 来自枚举1的项 type: string enum: - option A - option B - contains: title: 来自枚举2的项 type: string enum: - option C - option D - contains: title: 普通字符串项 type: string
代码说明
minItems: 3和maxItems: 3确保数组恰好有3个元素uniqueItems: true避免出现重复元素- 三个
contains分别要求数组中至少有一个元素对应枚举1、枚举2、普通字符串,结合数组长度为3的约束,就能保证三种类型各出现一次
如果要求元素顺序固定(比如第一个必须是枚举1,第二个是枚举2,第三个是普通字符串),可以用OpenAPI 3.1+支持的prefixItems:
filters: type: array minItems: 3 maxItems: 3 uniqueItems: true prefixItems: - title: 枚举1项 type: string enum: - option A - option B - title: 枚举2项 type: string enum: - option C - option D - title: 普通字符串项 type: string
内容的提问来源于stack exchange,提问作者Ara Medina
相关产品推荐
相关产品推荐

