我有一个 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/