如何自定义SpringWebFlux WebClient JSON反序列化?

2023-12-21

我正在使用一个spring-webflux WebClient https://docs.spring.io/spring/docs/5.0.0.BUILD-SNAPSHOT/javadoc-api/org/springframework/web/reactive/function/client/WebClient.html(内部版本 20170502.221452-172)访问生成流的 Web 应用程序Entry像这样的对象(应用程序/流+json):

final WebClient producerClient = WebClient.create("http://localhost:8080/");

Flux<Entry> entries = producerClient.get().uri("json-stream")
        .accept(MediaType.APPLICATION_STREAM_JSON)
        .exchange()
        .flatMapMany(clientResponse -> clientResponse.bodyToFlux(Entry.class));

虽然反序列化Entry对象对于使用标准通用类型(包括 Java 时间(JSR-310)数据类型,如 java.time.Instant)的 POJO 工作得很好,我想知道我需要做什么才能将任何自定义 JSON 添加到 Java 反序列化(例如,自定义 Jackson ObjectMapper) )。

我找不到任何 API网络客户端 https://docs.spring.io/spring/docs/5.0.0.BUILD-SNAPSHOT/javadoc-api/org/springframework/web/reactive/function/client/WebClient.html或者在其构建器和流畅的 API 生成的对象的类中执行此操作。

有人使用过带有自定义反序列化的 WebClient 吗?

(也许 API 还没有?)


这是一个自定义的示例ObjectMapper用于 JSON 序列化(反序列化)。 请注意,出于流媒体目的,使用了不同的编码器/解码器,但其配置原理保持不变。

    ExchangeStrategies strategies = ExchangeStrategies
            .builder()
            .codecs(clientDefaultCodecsConfigurer -> {
                clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonEncoder(new Jackson2JsonEncoder(new ObjectMapper(), MediaType.APPLICATION_JSON));
                clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(new ObjectMapper(), MediaType.APPLICATION_JSON));

            }).build();

    WebClient webClient = WebClient.builder().exchangeStrategies(strategies).build();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何自定义SpringWebFlux WebClient JSON反序列化? 的相关文章

随机推荐