java - Spring WebClient toEntityList 不适用于 List<String>

标签 java spring rest spring-webclient

我有一个 REST 端点,它返回一个简单的字符串 ID JSON 数组:

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

响应有Content-Type: application/json .

我正在从 Spring WebClient 中消耗它,并且正在尝试生成 List<String>使用toEntityList方法:

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

但是,这并没有正确解析 JSON,而是返回一个包含单个项目的列表,并且该项目是响应的文字字符串内容,如上所示。

同样的模式对于 String 以外的列表项类型也适用。 (通常是 JSON 对象)。

有没有办法告诉Spring将响应解析为它声明自己的JSON?

最佳答案

根据rstoyanchev's comment on the issue "WebClient decodes string array as one string"这种行为是故意的。

This is described here https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-codecs-jackson.

There is an ambiguity with String and "application/json". It could be a serialized JSON text or a JSON array. We treat it as the former for several reasons. One because you can resolve the ambiguity with a target of Mono<List> whereas the other way around there would be no option. Two because it avoids other issues with SSE streams. Three because JSON Strings are less common and a slightly less longer syntax seems acceptable.

bringyou mentions此解决方法:

webClient.get().uri().retrieve().bodyToFlux(String[].class);   // now we get a flux<String[]> which only has one item
webClient.get().uri().retrieve().bodyToMono(String[].class);  // or a mono<String[]>

另一个解决方案可能是更改 REST 端点以返回以行分隔的字符串 ID 列表,而不是 JSON 数组。根据Spring Reactive Jackson JSON documentation ,Jackson 解码器支持“任何行分隔的 JSON 格式,例如 NDJSON、JSON 行或 JSON 文本序列”。如果您使用 Jackson 作为 REST 端点,则在客户端中 accept(MediaType.APPLICATION_NDJSON) 并将 products=MediaType.APPLICATION_NDJSON_VALUE 添加到 REST Controller 就足够了.

关于java - Spring WebClient toEntityList 不适用于 List<String>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75827198/

相关文章:

java - Hibernate 或 Java 中是否有类似于 PHP $_SESSION 的 Session 变量

java - 有没有办法在不使用 Spring 的情况下将 Java 连接到 React?

java - Clob 对象数据为空

java - Clojure:交叉引用变量、声明和编译错误

java - org.springframework.util.Assert 在我的 Surefire 报告中显示为错误,而实际上它应该是失败

java - 创建 bean 时出错, Autowiring 失败

python - 如何使用 Django REST 框架在 Spyder IDE 中启动新的 Web 应用程序

javascript - 放置、修补和删除不会返回错误

java - 如何在 Drools 中通过 Java API 操作引导决策表?

java - Android,设置背景拉伸(stretch)或放大但永远不会正确