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

如何用OpenAPI-MicroProfile正确标注返回HashMap<String,List>的Java API

正确标注返回HashMap<String, List>类型的OpenAPI方案

问题分析

你之前用SchemaType.ARRAY标注会让Swagger显示数组结构,和HashMap的键值对结构不符;自定义继承HashMap的类时,因未明确泛型类型,导致序列化异常仅返回字符串。以下是两种可行的解决方法:


方案1:直接通过@Schema定义键值对结构

无需自定义类,直接在@Schema中指定对象类型,并通过additionalProperties定义值的结构:

@GET
@Path("/")
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON})
@Operation(summary = "All grunddata for applikationen")
@APIResponse(
        responseCode = "200",
        description = "All grunddata in the system",
        content = @Content(
                schema = @Schema(
                        type = SchemaType.OBJECT,
                        additionalProperties = @Schema(
                                type = SchemaType.ARRAY,
                                implementation = Grunddata.class
                        )
                )
        )
)

该配置会让Swagger正确识别返回结构为:字符串类型的键,对应Grunddata对象组成的数组值,完全匹配HashMap<String, List<Grunddata>>。


方案2:创建明确泛型的自定义HashMap子类

如果偏好使用自定义类,需明确泛型参数,避免序列化丢失类型信息:

1. 定义自定义类

public class GrunddataMap extends HashMap<String, List<Grunddata>> {
    // 无需额外代码,继承HashMap的所有方法即可
}

2. 在API注解中使用该类

@GET
@Path("/")
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON})
@Operation(summary = "All grunddata for applikationen")
@APIResponse(
        responseCode = "200",
        description = "All grunddata in the system",
        content = @Content(
                schema = @Schema(implementation = GrunddataMap.class)
        )
)

此方式下,序列化框架(如Jackson)能正确识别泛型结构,Swagger也会展示对应的键值对返回类型。


注意事项

  • 确保你的JSON序列化框架支持泛型类型的正确解析,避免因类型擦除导致的序列化异常。
  • 方案1仅适用于OpenAPI 3.x版本,该版本原生支持additionalProperties属性。

内容的提问来源于stack exchange,提问作者user3827141

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 11:20:28