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

Spring WebClient toEntityList处理List<String>失效,如何正确解析JSON?

问题描述

REST端点返回由字符串ID组成的JSON数组,格式如下:

["D0000019","D0000017","D0000016","D0000013","D0000009","D0000020"]

该响应的Content-Type为application/json。使用Spring WebClient调用此端点时,尝试通过toEntityList方法生成List<String>,代码如下:

ResponseEntity<List<String>> response = webClient.get()
    .uri("/myEndpoint")
    .accept(MediaType.APPLICATION_JSON)
    .retrieve()
    .toEntityList(String.class)
    .block();

但解析结果不符合预期:返回的列表仅包含一个元素,即整个JSON响应的字面字符串内容。而相同的调用模式对JSON对象组成的列表可以正常解析,需要解决如何让Spring正确解析该字符串数组的问题。

解决方案

问题根源在于直接传入String.class时,Spring会将整个JSON响应体视为单一字符串,而非字符串数组。正确的做法是通过ParameterizedTypeReference明确指定泛型类型List<String>,让消息转换器能够正确识别并解析数组:

ResponseEntity<List<String>> response = webClient.get()
    .uri("/myEndpoint")
    .accept(MediaType.APPLICATION_JSON)
    .retrieve()
    .toEntity(new ParameterizedTypeReference<List<String>>() {})
    .block();

如果不需要获取ResponseEntity,仅需列表内容,可简化为:

List<String> ids = webClient.get()
    .uri("/myEndpoint")
    .accept(MediaType.APPLICATION_JSON)
    .retrieve()
    .bodyToMono(new ParameterizedTypeReference<List<String>>() {})
    .block();

ParameterizedTypeReference的作用是保留泛型类型信息,避免类型擦除导致Spring无法正确识别目标类型,从而实现JSON数组到List<String>的正确解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 11:57:23