如何自定义SpringWebFlux WebClient JSON反序列化? [英] How to customize SpringWebFlux WebClient JSON deserialization?

查看:1128
本文介绍了如何自定义SpringWebFlux WebClient JSON反序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用

I'm using a spring-webflux WebClient (build 20170502.221452-172) to access a Web application producing a stream of Entry objects (application/stream+json) like this:

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 time(JSR-310)数据类型,如java.time)的POJO正常工作,但我不知道我该怎么做为了向Java反序列化添加任何自定义JSON(例如,自定义Jackson的ObjectMapper).

While the deserialization of the Entry objects works fine for POJOs using standard common types including Java time (JSR-310) datatypes like java.time.Instant, I wonder what I would have to do in order to add any custom JSON to Java deserialization (e. g., a custom Jackson ObjectMapper).

我在

I can't find any API in WebClient or in the classes of the objects produced by its builder and fluent APIs to do that.

有人使用WebClient进行自定义反序列化吗?

Has anybody used WebClient with customized deserialization?

(也许API还不存在?)

(Maybe the API is not there, yet?)

推荐答案

以下是为JSON(反序列化)自定义ObjectMapper的示例. 请注意,出于流式传输的目的,正在使用不同的编码器/解码器,但是其配置原理相同.

Here's an example that customizes the ObjectMapper for JSON (de)serialization. Note that for streaming purposes, different encoders/decoders are being used but the principle remains the same for their configuration.

    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();

这篇关于如何自定义SpringWebFlux WebClient JSON反序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆