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_ ...
随机推荐
- JAVA 基础编程练习题35 【程序 35 最大最小交换】
35 [程序 35 最大最小交换] 题目:输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组. package cskaoyan; public class cskaoyan35 { ...
- asp.net mvc 中Html.ValidationSummary显示html
@if (!ViewData.ModelState.IsValid) { <div>@Html.Raw(HttpUtility.HtmlDecode(Html.ValidationSumm ...
- iOS面试-堆和栈的区别
堆和栈的区别: 一.堆栈空间分配区别: 1.栈(操作系统):由操作系统自动分配释放 ,存放函数的参数值,局部变量的值等.其操作方式类似于数据结构中的栈: 2.堆(操作系统): 一般由程序员分配释放, ...
- MySQL数据库相关资料
python 全栈开发,Day60(MySQL的前戏,数据库概述,MySQL安装和基本管理,初识MySQL语句) python 全栈开发,Day61(库的操作,表的操作,数据类型,数据类型(2),完整 ...
- 怎么理解linux作业(job),与进程(process)的关系
1.相关概念: shell :命令解释器,其实就是一个脚本语言解释器,有很多种(bash,ash,tcsh等),最常用的是bash. job(作业): 是相对shell 来说的,在shell中执行一条 ...
- beego conf配置文件
1. 多个配置文件通过include引入 自定义配置文件mysql.conf 在app.conf 中引入mysql.conf include "mysql.conf"
- ue-cli3 取消eslint校验代码
参考链接:https://www.cnblogs.com/sjie/p/9884362.html
- 文件input框选择图片实时显示小技巧
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- storm group 的介绍与使用
一.stream group分组介绍 Stream 的分组分为随机分组.字段分组.全部分组.全局分组.无分组.直接分组,自定义分组 二.group的介绍 1.Shuffle grouping:通过tu ...
- [转帖]龙芯:Docker 配置与实践清单
Docker 配置与实践清单 http://www.sohu.com/a/254904706_198222 文章对来官方文档及 Docker Links[1] 中链接内容进行归档整理,包含了日常工作中 ...