第一步:移除jackson依赖
参考代码
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!-- 排除jackson依赖 --> <exclusions> <exclusion> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </exclusion> </exclusions> </dependency>
第二步:加入gson依赖
参考代码
<!-- 添加Gson依赖 --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> </dependency>
完成
ps:进入WebMvcConfigurationSupport.java可以看到源码
可以看到有这两个常量
private static final boolean jackson2Present = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", WebMvcConfigurationSupport.class.getClassLoader()) && ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", WebMvcConfigurationSupport.class.getClassLoader()); private static final boolean gsonPresent = ClassUtils.isPresent("com.google.gson.Gson", WebMvcConfigurationSupport.class.getClassLoader());
一个是我们加入的gson,另一个则是jackson了。
其中还有这样一个方法,用来返回messageConverters
protected final List<HttpMessageConverter<?>> getMessageConverters() { if (this.messageConverters == null) { this.messageConverters = new ArrayList<>(); configureMessageConverters(this.messageConverters); if (this.messageConverters.isEmpty()) { addDefaultHttpMessageConverters(this.messageConverters); } extendMessageConverters(this.messageConverters); } return this.messageConverters; }
通过查看addDefaultHttpMessageConverters这个方法,可以看到它是先判断jackson2Present是否存在
存在则往messageConverters中加入MappingJackson2HttpMessageConverter
即如果gson和jackson同时存在则先判断jackson加入MappingJackson2HttpMessageConverter
if (jackson2Present) { Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.json(); if (this.applicationContext != null) { builder.applicationContext(this.applicationContext); } messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build())); } else if (gsonPresent) { messageConverters.add(new GsonHttpMessageConverter()); }
因此,如果出现无法排除jackson等特殊情况,可以通过重写extendMessageConverters方法来使getMessageConverters方法返回一个修改过的messageConverters(就是下面这个集合)
private List<HttpMessageConverter<?>> messageConverters;
继承WebMvcConfigurationSupport,重写extendMessageConverters方法,再删除其中的MappingJackson2HttpMessageConverter,加入GsonHttpMessageConverter
参考代码
@Configuration @EnableWebMvc public class GsonUtils extends WebMvcConfigurationSupport { @Override protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) { converters.removeIf(httpMessageConverter -> httpMessageConverter instanceof MappingJackson2HttpMessageConverter); converters.add(new GsonHttpMessageConverter()); super.extendMessageConverters(converters); } }
还可以参考这种方法:https://www.jianshu.com/p/0b1f376bce5b
————————————————
版权声明:本文为CSDN博主「fwens」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_39885435/article/details/82624067