springboot升级2.0 fastjson报错? 2.0以上应该怎么整合fastjson?
SpringBoot2.0如何集成fastjson?在网上查了一堆资料,但是各文章的说法不一,有些还是错的,可能只是简单测试一下就认为ok了,最后有没生效都不知道。恰逢公司项目需要将JackSon换成fastjson,因此自己来实践一下SpringBoot2.0和fastjson的整合,同时记录下来方便自己后续查阅。
一、Maven依赖说明
<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 {}
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
中的write
和writeInternal
打了断点,再次执行,竟然什么都没有发生,根本没有走这两个方法,于是在自定义的SpringMvcConfigure
中configureMessageConverters
方法内打了断点,想看看这个方法参数converters
里边到底有什么:
@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);
}
}
总结
- 最重要的还是解决了springboot2.0.2配置fastjson不生效的问题
- 更加明白stream api返回的都是全新的对象
- 更理解java是值传递而不是引用传递
- 了解到想要在迭代过程中对集合进行操作要用Iterator,而不是直接简单的for循环或者增强for循环
springboot升级2.0 fastjson报错? 2.0以上应该怎么整合fastjson?的更多相关文章
- SpringBoot与jackson.databind兼容报错问题
SpringBoot与jackson.databind兼容报错问题 ———————————————— 1.SpringBoot版本V2.0.0其依赖的jackson-databind版本为V2.9.4 ...
- Tomcat7.0启动报错:java.lang.illegalargumentexception:taglib definition not consisten with specification version
Tomcat7.0启动报错:java.lang.illegalargumentexception:taglib definition not consisten with specification ...
- wince6.0 编译报错:"error C2220: warning treated as error - no 'object' file generated"的解决办法
内容提要:wince6.0编译报错:"error C2220: warning treated as error - no 'object' file generated" 原因是 ...
- 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 ...
- 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报错,用到注解的 ...
- 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 ...
- 01-路由跳转 安装less this.$router.replace(path) 解决vue/cli3.0语法报错问题
2==解决vue2.0里面控制台包的一些语法错误. https://www.jianshu.com/p/5e0a1541418b 在build==>webpack.base.conf.j下注释掉 ...
- Mybatis传多个参数的问题 及MyBatis报错 Parameter '0' not found. Available parameters are [arg1, arg0, param1 问题
对于使用Mybatis ,传多个参数,我们可以使用对象封装外,还可以直接传递参数 对象的封装,例如查询对象条件basequery对象 <select id="getProductByP ...
- Ubuntu系统---报错Assertion '0' failed
Ubuntu系统---报错Assertion '0' failed YOLO V3,CUDA Error: out of memory darknet: ./src/cuda.c:36: check_ ...
随机推荐
- CDH集群部署hive建表中文乱码
背景:部署CDH集群的 hive 服务,选用 mysql 作为 hive 元数据的存储数据库,通过 hive cli 建表时发现中文注释均乱码. 现象:hive端建表中文注释乱码. 定位: 已经确认过 ...
- ubuntu下virtualbox的安装、卸载
一.添加VirtualBox的源并安装5.1版本 virtualbox官网:https://www.virtualbox.org/wiki/Download_Old_Builds 虽然也可以直接安装d ...
- JavaScript:undefined!=false之解 及==比较的规则
JS中有一个基本概念就是: JavaScript中undefined==null 但undefined!==null undefined与null转换成布尔值都是false 如果按照常规想法,比如下面 ...
- java面试考点-HashTable/HashMap/ConcurrentHashMap
HashTable 内部数据结构是数组+链表,键值对不允许为null,线程安全,但是锁是整表锁,性能较差/效率低 HashMap 结构同HashTable,键值对允许为null,线程不安全, 默认初始 ...
- 360安全卫士11.0史上最小版发布,去流氓,最精简,300MB内存轻松运行。完全不拖慢电脑的速度,由王宁诚意发布。
360安全卫士11.0史上最小版发布,也是史上最快版本.大家可能都不喜欢360,为什么?因为360太流氓,而大家想过如果360去掉了流氓会怎么样?对,那样360就会变成一个性能可以超过知名杀毒软件-s ...
- spring boot工程如何启用 热启动功能
1.在pom.xml里面添加一个依赖即可 关键代码 <dependency> <groupId>org.springframework.boot</groupId> ...
- .Net WebApi接口之Swagger集成详解
本文详细的介绍了.net从一个新的项目中创建api后集成swagger调试接口的流程! 1.首先我们创建一个MVC项目(VS2012): 2.然后在项目中的Controllers文件夹中添加API接口 ...
- zTree入门使用
简单入门使用,熟悉其功能,没有与异步调用后台数据,用的是本地设置的数据. zTree的API:http://www.treejs.cn/v3/api.php 源码:https://github.com ...
- 【转】转载一篇优质的讲解epoll模型的文章
从事服务端开发,少不了要接触网络编程.Epoll 作为 Linux 下高性能网络服务器的必备技术至关重要,Nginx.Redis.Skynet 和大部分游戏服务器都使用到这一多路复用技术. Epoll ...
- Java网络编程面试总结
转载. https://blog.csdn.net/qq_39470733/article/details/84635274 1.GET 和 POST 的区别? GET 请求可被缓存 GET 请求保留 ...