小编Cha*_*lie的帖子

Spring反应式WebClient GET json响应内容类型为“text/plain;charset=UTF-8”

我遇到了 Spring 5 反应式 WebClient 的问题,当我请求一个端点,该端点返回内容类型为“text/plain;charset=UTF-8”的格式正确的 json 响应。例外是

org.springframework.web.reactive.function.UnsupportedMediaTypeException:
Content type 'text/plain;charset=UTF-8' not supported for bodyType=MyDTOClass
Run Code Online (Sandbox Code Playgroud)

这是我提出请求的方式:

webClient.get().uri(endpoint).retrieve().bodyToFlux(MyDTOClass.class)
Run Code Online (Sandbox Code Playgroud)

编辑:标题已“正确”设置(接受、内容类型),我尝试了不同的内容类型(json、json + UTF8、纯文本、纯文本 + UTF8)组合,但没有成功。我认为问题是.bodyToFlux(MyDTOClass.class)不知道如何将“文本”翻译成MyDTOClass对象。如果我将请求更改为:

webClient.get().uri(endpoint).retrieve().bodyToFlux(String.class)
Run Code Online (Sandbox Code Playgroud)

我可以读取字符串。

编辑 2:下一个引用是从 Spring 文档中提取的(https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-codecs-jackson)

默认情况下,Jackson2Encoder和Jackson2Decoder都不支持 type 元素String。相反,默认假设是一个字符串或一系列字符串表示序列化的 JSON 内容,由CharSequenceEncoder. 如果您需要从 呈现 JSON 数组Flux<String>,请使用Flux#collectToList()并编码 Mono<List<String>>.

我认为解决方案是定义一个新的解码器/阅读器,以便将字符串转换为 MyDTOClass,但我不知道该怎么做。

reactive-programming jackson spring-boot spring-webflux

3
推荐指数
1
解决办法
6028
查看次数