在 Spring Webflux 中使用 Gson 而不是 Jackson

Lyu*_*yux 6 spring jackson gson spring-boot spring-webflux

我们已经有很多 Spring MVC 项目,它们都使用 gson 而不是 jackson 进行响应体编码。我们的bean类都是基于gson注解编写的。现在我正在设置一个 Spring Webflux 宁静服务器。如果我们可以使用 Spring MVC 项目中的旧 bean 类,将会节省大量工作。

我试过spring.http.converters.preferred-json-mapper=gson财产无济于事。

我试过HttpMessageConverterbean,它包含在 webflux 包中,但它不像在 Spring MVC 项目中那样工作。

我在谷歌上搜索了很多,唯一有用的是实现org.springframework.http.codec.HttpMessageEncoder类并将其设置为WebFluxConfigurer.configureHttpMessageCodecs()方法:

@Configuration
public class WebConfiguration implements WebFluxConfigurer {
    @Override
    public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
        configurer.customCodecs().decoder(new GsonHttpMessageDecoder());
        configurer.customCodecs().encoder(new GsonHttpMessageEncoder());
    }

    private static class GsonHttpMessageEncoder implements HttpMessageEncoder {
        ...
    }

    private static class GsonHttpMessageDecoder implements HttpMessageDecoder {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

我还没有尝试过,因为它有点复杂。有没有什么简单的方法可以在 Spring Webflux 中用 gson 替换 jackson?

任何帮助表示赞赏。

Bri*_*zel 2

Spring框架目前不支持GSON作为WebFlux Encoder/ 。Decoder欢迎关注专题问题

请注意,据我所知,GSON 不支持非阻塞解析,因此即使在 Framework 中实现了支持,它也不会完整,并且不应该涵盖流输入用例。