无法从 Flux<String> 转换为 List<String>
Unable to convert from Flux<String> to List<String>
我在我的项目中使用 Spring webflux 与外部 API 进行通信。
在我的项目中,我无法将 Flux 转换为 List。
在尝试对 collectList().block() 执行相同操作时,flux 的所有元素都连接到一个字符串并存储在列表的第 0 个索引处。
如果我 return Flux 而不是 List 那么它会发送预期的响应。但我需要操纵内容并将其作为子对象添加到其他对象,因此尝试 return 列表。
public List<String> retrieveWebLogin(String platformId) {
try {
ClientResponse response = webClient
.get()
.uri(EV_LEGACY_WEB_RTC_ENDPOINT_API_PATH)
.accept(APPLICATION_JSON)
.exchange().block();
Flux<String> uriFlux = response.bodyToFlux(String.class);
List<String> uriList = uriFlux.collectList().block();
return uriList;
} catch (Exception e) {
logger.info(e.getMessage(), e);
}
return null;
}
预期结果:
[
"agent1",
"agent2"
]
实际结果:
“["agent1","agent2"]”
您的代码应该如下所示。
final List<String> uriList = webClient
.get()
.uri(EV_LEGACY_WEB_RTC_ENDPOINT_API_PATH)
.accept(MediaType.APPLICATION_JSON_UTF8)
.exchange()
.flatMap(response -> response.bodyToMono(new ParameterizedTypeReference<List<String>>() {}))
.block();
我在我的项目中使用 Spring webflux 与外部 API 进行通信。 在我的项目中,我无法将 Flux 转换为 List。
在尝试对 collectList().block() 执行相同操作时,flux 的所有元素都连接到一个字符串并存储在列表的第 0 个索引处。 如果我 return Flux 而不是 List 那么它会发送预期的响应。但我需要操纵内容并将其作为子对象添加到其他对象,因此尝试 return 列表。
public List<String> retrieveWebLogin(String platformId) {
try {
ClientResponse response = webClient
.get()
.uri(EV_LEGACY_WEB_RTC_ENDPOINT_API_PATH)
.accept(APPLICATION_JSON)
.exchange().block();
Flux<String> uriFlux = response.bodyToFlux(String.class);
List<String> uriList = uriFlux.collectList().block();
return uriList;
} catch (Exception e) {
logger.info(e.getMessage(), e);
}
return null;
}
预期结果: [ "agent1", "agent2" ]
实际结果: “["agent1","agent2"]”
您的代码应该如下所示。
final List<String> uriList = webClient
.get()
.uri(EV_LEGACY_WEB_RTC_ENDPOINT_API_PATH)
.accept(MediaType.APPLICATION_JSON_UTF8)
.exchange()
.flatMap(response -> response.bodyToMono(new ParameterizedTypeReference<List<String>>() {}))
.block();