You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 17:24:55