如何通过Swagger注解实现动态字符串值查询参数的正确定义?
如何用Swagger注解实现动态字符串值的查询参数
你可以通过调整Swagger注解中additionalPropertiesSchema的写法来实现正确的OpenAPI定义,问题出在之前直接传入String.class会被解析为object类型,需要明确指定值的类型为字符串。
正确的注解写法
@Parameter(in = ParameterIn.QUERY, name = "filters", description = "Filters to apply to the search", style = ParameterStyle.FORM, explode = Explode.TRUE, schema = @Schema(implementation = Map.class, additionalProperties = true, additionalPropertiesSchema = @Schema(type = "string")))
问题原因说明
你之前使用additionalPropertiesSchema = String.class时,Swagger会将其识别为对Java String类的引用,默认生成type: object的schema。而通过@Schema(type = "string")显式指定类型,就能让生成的OpenAPI规范中additionalProperties的类型正确显示为string。
生成的正确YAML片段
使用上述注解后,生成的OpenAPI内容会和你期望的一致:
parameters: - name: filters in: query description: Filters to apply to the search style: form explode: true schema: type: object additionalProperties: type: string
内容的提问来源于stack exchange,提问作者basbe
相关产品推荐
相关产品推荐

