在 Spring Webflux 中使用 Gson 而不是 Jackson

Using Gson instead of Jackson in Spring Webflux

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

我试过spring.http.converters.preferred-json-mapper=gson属性没用。

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

我用谷歌搜索了很多,唯一有用的是实现 org.springframework.http.codec.HttpMessageEncoder class 并将其设置为 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 {
        ...
    }
}

我还没有试过这个,因为它有点复杂。在 Spring Webflux 中有一些简单的方法可以用 gson 替换 jackson 吗?

感谢任何帮助。

Spring 框架目前不支持 GSON 作为 WebFlux Encoder / Decoder。随意 follow up on the dedicated issue.

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