SpringBoot2.0如何集成fastjson?在网上查了一堆资料,但是各文章的说法不一,有些还是错的,可能只是简单测试一下就认为ok了,最后有没生效都不知道。恰逢公司项目需要将JackSon换成fastjson,因此自己来实践一下SpringBoot2.0和fastjson的整合,同时记录下来方便自己后续查阅。

一、Maven依赖说明

  SpringBoot的版本为: <version>2.1.4.RELEASE</version>
  在pom文件中添加fastjson的依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60/version>
</dependency>
 

二、整合

  整合之前,我们先说下springboot1.0的方法,轻车熟路的去自定了一个SpringMvcConfigure去继承WebMvcConfigurerAdapter,然后你就发现这个WebMvcConfigurerAdapter竟然过时了?what?点进去看源码:

 /**
* An implementation of {@link WebMvcConfigurer} with empty methods allowing
* subclasses to override only the methods they're interested in.
*
* @author Rossen Stoyanchev
* @since 3.1
* @deprecated as of 5.0 {@link WebMvcConfigurer} has default methods (made
* possible by a Java 8 baseline) and can be implemented directly without the
* need for this adapter
*/
@Deprecated
public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {}
 
  可以看到从spring5.0开始就被@Deprecated,原来是java8中支持接口中有默认方法,所以我们现在可以直接实现WebMvcConfigurer,然后选择性的去重写某个方法,而不用实现它的所有方法.
 
  于是就实现了WebMvcConfigurer:
 
 @Configuration
public class SpringMvcConfigure implements WebMvcConfigurer { /**
* 配置消息转换器
* @param converters
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
//自定义配置...
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(SerializerFeature.QuoteFieldNames,
SerializerFeature.WriteEnumUsingToString,
/*SerializerFeature.WriteMapNullValue,*/
SerializerFeature.WriteDateUseDateFormat,
SerializerFeature.DisableCircularReferenceDetect);
fastJsonHttpMessageConverter.setFastJsonConfig(config);
converters.add(fastJsonHttpMessageConverter);
} }
 
  本以为这样子配置就可以完事儿,但是诡异的事情发生了,我明明注释了SerializerFeature.WriteMapNullValue,可是返回的json中仍然有为null的字段,然后我就去com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter中的writewriteInternal打了断点,再次执行,竟然什么都没有发生,根本没有走这两个方法,于是在自定义的SpringMvcConfigureconfigureMessageConverters方法内打了断点,想看看这个方法参数converters里边到底有什么:
 

  看到这里就想到,肯定是我自己添加的fastjson在后边,所以没有生效,所以就加了以下代码:
 
 @Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters = converters.stream()
.filter((converter)-> !(converter instanceof MappingJackson2HttpMessageConverter))
.collect(Collectors.toList());
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
//自定义配置...
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(SerializerFeature.QuoteFieldNames,
SerializerFeature.WriteEnumUsingToString,
/*SerializerFeature.WriteMapNullValue,*/
SerializerFeature.WriteDateUseDateFormat,
SerializerFeature.DisableCircularReferenceDetect);
fastJsonHttpMessageConverter.setFastJsonConfig(config);
converters.add(fastJsonHttpMessageConverter);
}
 
  这还是不生效的,继续追踪,得出如下结论:
     (1)源码分析可知,返回json的过程为:
Controller调用结束后返回一个数据对象,for循环遍历conventers,找到支持application/json的HttpMessageConverter,然后将返回的数据序列化成json。
具体参考org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor的writeWithMessageConverters方法
(2)由于是list结构,我们添加的fastjson在最后。因此必须要将jackson的转换器删除,不然会先匹配上jackson,导致没使用fastjson
  最终得出代码如下:
 
 @Configuration
public class SpringWebMvcConfigurer implements WebMvcConfigurer { private final Logger logger = LoggerFactory.getLogger(SpringWebMvcConfigurer.class); //使用阿里 FastJson 作为JSON MessageConverter
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { /*
先把JackSon的消息转换器删除.
备注: (1)源码分析可知,返回json的过程为:
Controller调用结束后返回一个数据对象,for循环遍历conventers,找到支持application/json的HttpMessageConverter,然后将返回的数据序列化成json。
具体参考org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor的writeWithMessageConverters方法
(2)由于是list结构,我们添加的fastjson在最后。因此必须要将jackson的转换器删除,不然会先匹配上jackson,导致没使用fastjson
*/
for (int i = converters.size() - 1; i >= 0; i--) {
if (converters.get(i) instanceof MappingJackson2HttpMessageConverter) {
converters.remove(i);
}
} FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(
SerializerFeature.WriteMapNullValue,//保留空的字段
SerializerFeature.WriteNullStringAsEmpty,//String null -> ""
SerializerFeature.WriteNullNumberAsZero,//Number null -> 0
SerializerFeature.WriteDateUseDateFormat);//日期格式化 converter.setFastJsonConfig(config);
converter.setDefaultCharset(Charset.forName("UTF-8"));
converters.add(converter);
}
}

  总结

  1. 最重要的还是解决了springboot2.0.2配置fastjson不生效的问题
  2. 更加明白stream api返回的都是全新的对象
  3. 更理解java是值传递而不是引用传递
  4. 了解到想要在迭代过程中对集合进行操作要用Iterator,而不是直接简单的for循环或者增强for循环

springboot升级2.0 fastjson报错? 2.0以上应该怎么整合fastjson?的更多相关文章

  1. SpringBoot与jackson.databind兼容报错问题

    SpringBoot与jackson.databind兼容报错问题 ———————————————— 1.SpringBoot版本V2.0.0其依赖的jackson-databind版本为V2.9.4 ...

  2. Tomcat7.0启动报错:java.lang.illegalargumentexception:taglib definition not consisten with specification version

    Tomcat7.0启动报错:java.lang.illegalargumentexception:taglib definition not consisten with specification ...

  3. wince6.0 编译报错:"error C2220: warning treated as error - no 'object' file generated"的解决办法

    内容提要:wince6.0编译报错:"error C2220: warning treated as error - no 'object' file generated" 原因是 ...

  4. Python2.7在Windows下CMD编码为65001/utf-8时print报错[Errno 0]/[Errno 2]

    使用python2.7处理unicode的字符串,环境变量已设置PYTHONIOENCODING为utf-8,cmd编码为utf-8时print unicode字符串会报错[Errno 0]或[Err ...

  5. AndroidStudio3.0 注解报错Annotation processors must be explicitly declared now. The following dependencies on the compile classpath are found to contain annotation processor.

    把Androidstudio2.2的项目放到3.0里面去了,然后开始报错了. 体验最新版AndroidStudio3.0 Canary 8的时候,发现之前项目的butter knife报错,用到注解的 ...

  6. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">报错

    https://blog.csdn.net/qq_36611526/article/details/79067159 今天遇到个问题 文件内引入某个资源 pom.xml头部http://maven.a ...

  7. 01-路由跳转 安装less this.$router.replace(path) 解决vue/cli3.0语法报错问题

    2==解决vue2.0里面控制台包的一些语法错误. https://www.jianshu.com/p/5e0a1541418b 在build==>webpack.base.conf.j下注释掉 ...

  8. Mybatis传多个参数的问题 及MyBatis报错 Parameter '0' not found. Available parameters are [arg1, arg0, param1 问题

    对于使用Mybatis ,传多个参数,我们可以使用对象封装外,还可以直接传递参数 对象的封装,例如查询对象条件basequery对象 <select id="getProductByP ...

  9. Ubuntu系统---报错Assertion '0' failed

    Ubuntu系统---报错Assertion '0' failed YOLO V3,CUDA Error: out of memory darknet: ./src/cuda.c:36: check_ ...

随机推荐

  1. TreeView如何实现选中的节点上移或下移 [问题点数:20分,结帖人nww2002]

    在TreeView中,如何实现选中一节点,右键点击上移或下移 TTreeNode.MoveTo() 一.获得Tree上的结点var NowNode : TTreeNode;begin  NowNode ...

  2. JavaScript基础------JavaScript语法

    js的注释与分号 // 单行注释 /**/多行注释 ctrl +shift +/ 语句结束使用分号,如果省略,则由解析器确定语句的结尾js语法 1.变量.函数名.操作符都区分大小写 2.标识符 (1) ...

  3. Linux nginx 会话保持(session)

    nginx 会话保持(session)有2种算法,一种是自带IP HASH 算法,一种是基于第三方模块sticky模块来实现会话保持 1)ip_hash 简单易用,但是有如下缺点 后端服务器宕机后,s ...

  4. modbus4j中使用modbus tcp/ip和modbus rtu over tcp/ip模式

    通过借鉴高人博客,总结如下: 1. TcpMaster类,用于生成ModbusMaster主类 package sun.sunboat; public class TcpMaster { privat ...

  5. Python学习笔记——文件系统

    文件系统 import os # 打印当前目录 print(os.getcwd()) # 列出当前目录的所有文件 print(os.listdir()) F:\codes\python\python\ ...

  6. SQL查询表的第一条数据和最后一条数据

    方法一: 使用TOP SELECT TOP 1 * FROM user; SELECT TOP 1 * FROM user order by id desc; 方法二: 使用LIMIT SELECT  ...

  7. 动态代理 aop切面实现事务管理

    1.定义接口和实现 public interface UserService { public String getName(int id); public Integer getAge(int id ...

  8. Python实现八大排序(基数排序、归并排序、堆排序、简单选择排序、直接插入排序、希尔排序、快速排序、冒泡排序)

    目录 八大排序 基数排序 归并排序 堆排序 简单选择排序 直接插入排序 希尔排序 快速排序 冒泡排序 时间测试 八大排序 大概了解了一下八大排序,发现排序方法的难易程度相差很多,相应的,他们计算同一列 ...

  9. pthread_cancel 相关

    假设线程A对线程B发出了一个取消请求.通过如下函数: #include <pthread.h> int pthread_cancel(pthread_t thread); 参数: thre ...

  10. 实现文件上下文管理(__enter__和___exit__)

    实现文件上下文管理(__enter__和__exit__) 我们知道在操作文件对象的时候可以这么写 with open('a.txt') as f: '代码块' 上述叫做上下文管理协议,即with语句 ...