Swagger 2.0判别器默认值配置与多态Schema有效性咨询
问题解答
关于多态映射的理解
你的理解完全正确。在Swagger 2.0的判别器机制中,如果animalType的取值(比如Horse、Cow)没有对应的子类Schema定义,系统会默认使用父类Animal的结构来解析数据。
现有Schema的问题及修正版本
你提供的Schema存在多处语法和结构错误,无法正常生效,具体问题及修正后的版本如下:
存在的问题
- YAML语法错误:
Animal的enum字段未按数组格式编写,缺少短横线前缀; - Schema结构错误:
Cat和Dog被写成了数组形式,Swagger 2.0要求Schema必须是对象,应通过allOf组合父类引用和自身属性; - 扩展字段错误:
Dog的x-ms-discriminator-value误写为'Cat',且Cat的该字段末尾多了无效逗号; - 判别器映射不明确:未显式指定判别器值与Schema的映射关系,虽然默认规则生效,但显式定义更清晰。
修正后的Schema
components: schemas: Animal: type: object required: - animalType properties: animalType: type: string enum: - 'Dog' - 'Horse' - 'Cow' - 'Cat' name: type: string discriminator: propertyName: animalType mapping: Dog: '#/components/schemas/Dog' Cat: '#/components/schemas/Cat' # Horse和Cow未指定映射,默认使用Animal Cat: allOf: - $ref: '#/components/schemas/Animal' - type: object properties: color: type: string x-ms-discriminator-value: 'Cat' Dog: allOf: - $ref: '#/components/schemas/Animal' - type: object properties: bark: type: string x-ms-discriminator-value: 'Dog'
关键说明
- 修正了
enum的数组格式,确保YAML语法合法; - 将
Cat和Dog调整为标准的allOf结构,正确继承Animal并添加自身属性; - 修正了
x-ms-discriminator-value的取值,确保与animalType的枚举值匹配; - 在
Animal的discriminator中添加了mapping字段,显式指定Dog和Cat的映射关系,Horse和Cow因未指定映射,会自动 fallback 到父类Animal,符合你的需求。
内容的提问来源于stack exchange,提问作者Amit Kumar
相关产品推荐
相关产品推荐

