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. 【ARTS】01_29_左耳听风-201900527~201900602

    ARTS: Algrothm: leetcode算法题目 Review: 阅读并且点评一篇英文技术文章 Tip/Techni: 学习一个技术技巧 Share: 分享一篇有观点和思考的技术文章 Algo ...

  2. MFC中使用ADO进行数据库操作

    参考FROM:http://hi.baidu.com/sunkanghome/item/e1fda510b3186359f1090ee2 数据库与数据库编程: 当前各种主流数据库有很多,包括Oracl ...

  3. MySql中的count、NULL和空串的区别

    **1.count (1).count (*) 与 count (列名) 的区别** 表 count(1) count(*) count (列名) 作用 统计表中的所有的记录数 会统计表中的所有的记录 ...

  4. 最新 苏宁java校招面经 (含整理过的面试题大全)

    从6月到10月,经过4个月努力和坚持,自己有幸拿到了网易雷火.京东.去哪儿.苏宁等10家互联网公司的校招Offer,因为某些自身原因最终选择了苏宁.6.7月主要是做系统复习.项目复盘.LeetCode ...

  5. PCM-FTL

    1. 运行时第一行需要是write 错误位置 trace_stat->sectors += length;

  6. [转帖]curl网站开发指南

    curl网站开发指南 http://www.ruanyifeng.com/blog/2011/09/curl.html linux 里面有非常多很好的工具 比如这个 curl 之前 以为 wget 就 ...

  7. shell备份脚本

    #!/bin/bash #不存在的变量终止脚本执行 set -o nounset #执行出错终止脚本执行 set -o errexit #递归列出文件的绝对路径并执行压缩 delDir=`date - ...

  8. Proxy 和aop

    Proxy 就是代理,意思就是 你不用去做,别人代替你去处理 先来个静态代理 public interface Hello { void say(String name); } 被代理类 public ...

  9. 关于container_of函数分析

    #include <stdio.h> #define offset_of(type,member) ((int)&(((type *)0)->member)) #define ...

  10. 测试常用__linux命令

    1.显示目录和文件的命令 Ls:用于查看所有文件夹的命令. Dir:用于显示指定文件夹和目录的命令 Tree: 以树状图列出目录内容 Du:显示目录或文件大小 2.修改目录,文件权限和属主及数组命令 ...