OpenAPI Parser (Light-4J) oneOf规则验证异常问题求助
关于Light-4J 2.0.10中JSON Schema oneOf验证异常的问题
示例1:oneOf多匹配未触发验证失败
Schema定义
components: schemas: GroupHeader114: # clause 1 type: object properties: Authstn: type: object oneOf: - type: object properties: Cd: type: string enum: - AUTH - FDET - type: object properties: Prtry: type: string enum: - ABC - DDD
请求Payload
{ "GroupHeader114": { "Authstn": { "Cd": "AUTH", "Prtry": "DDD" } } }
问题描述
该Payload同时包含Cd和Prtry字段,理论上应同时匹配oneOf下的两个子Schema,触发oneOf验证失败,但实际验证通过,疑似验证器存在Bug。
原因分析与解决
JSON Schema的oneOf默认仅校验目标是否匹配其中一个子Schema,但如果子Schema未设置additionalProperties: false,额外字段不会导致该子Schema匹配失败。示例中两个子Schema仅定义允许的属性,不禁止额外属性,因此Payload同时包含两个字段时,两个子Schema都会判定为匹配,部分旧版本验证器对这种场景的处理不符合规范。
解决方法:在每个oneOf的子Schema中添加additionalProperties: false,明确禁止额外属性:
components: schemas: GroupHeader114: # clause 1 type: object properties: Authstn: type: object oneOf: - type: object properties: Cd: type: string enum: - AUTH - FDET additionalProperties: false - type: object properties: Prtry: type: string enum: - ABC - DDD additionalProperties: false
示例2:合法Payload触发oneOf验证错误
Schema定义(修正语法错误后)
components: schemas: GroupHeader114: # clause 1 type: object properties: GroupHeader114: type: object properties: Authstn: type: array maxItems: 2 items: $ref: '#/components/schemas/Authorisation1Choice' Authorisation1Choice: oneOf: - $ref: '#/components/schemas/AuthorisationCodeCd' - $ref: '#/components/schemas/Max128TextPrtry' Max128Text: type: string minLength: 1 maxLength: 128 Max128TextPrtry: type: object properties: Prtry: $ref: '#/components/schemas/Max128Text' Authorisation1Code: type: string enum: - AUTH - FDET - FSUM - ILEV Authorisation1CodeCd: type: object properties: Cd: $ref: '#/components/schemas/Authorisation1Code'
请求Payload(修正格式错误后)
{ "GroupHeader114": { "GroupHeader114": { "Authstn": [ { "Cd": "AUTH" } ] } } }
问题描述
Payload仅包含Cd字段,理论上应匹配AuthorisationCodeCd子Schema,符合oneOf要求,但收到错误提示:requestBody.GroupHeader114.Authstn[0]: should be valid to one and only one of the schemas。
原因分析与解决
原Schema和Payload存在多处错误导致验证异常:
- Schema语法错误:原
$ref路径使用.替代/,且缺少冒号,导致验证器无法正确解析引用的子Schema; - Payload结构不匹配:Schema中
Authstn的层级为GroupHeader114.GroupHeader114.Authstn,但原Payload直接将Authstn放在顶层GroupHeader114下,层级不对应; - Payload格式错误:数组未闭合、大括号不完整,导致JSON解析失败。
修正上述错误后,验证器可正确识别Payload仅匹配一个子Schema,通过验证。
内容的提问来源于stack exchange,提问作者yapkm01
相关产品推荐
相关产品推荐

