本人以往的项目,一律是使用fastjson的1系列版本,虽然经历过几次的重大bug的事件,但是即使升级,也没有什么!
毕竟就算是官方的Jackson的也爆出过bug事件呢!
程序嘛,没有一些bug什么的,真的不完美…神器都是经过不断迭代更新与不断优化的
本章内容
相信网络上,关于springboot设置fastjson做序列化与反序列化的文章,多如牛毛,本周将对一些通用的使用方法忽略带过,对于一些高级应用方式将详细阐述…
- springboot接入fastjson2的配置
- 重写或者扩展或者覆盖springboot中关于json的转换器
- 扩展fastjson2相关类方法,充分发挥其强大能量
- fastjson2作为数据传播介质,减少DTO或者DO等中间封装类,灵活组装数据,简化系统代码量
一、springboot接入fastjson2的配置
思路:
- 排除掉springboot默认使用的Jackson;
- 加入Fastjson2的依赖
1.排除默认的Jackson
<!-- spring boot web--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><exclusions><!-- 去掉Jackson依赖,用fastjson --><exclusion><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-json</artifactId></exclusion></exclusions></dependency>
2.加入Fastjson2的依赖
截止于今天2022-10-10,Fastjson2最新版本为2.0.15
<properties><fastjson.version>2.0.15</fastjson.version></properties><dependency><groupId>com.alibaba.fastjson2</groupId><artifactId>fastjson2-extension</artifactId><version>${fastjson.version}</version></dependency>
二、重写或者扩展或者覆盖springboot中关于json的转换器
关键字:Fastjson2,springboot序列化与反序列化,HttpMessageConverter
关联类:JSONWebMvcConfigurer.java
- springboot对json的转换,包括序列化与反序列化,都是通过一定的转换器来指定转换规则,无论是默认的Jackson还是Fastjson2,都一样。
- 只要修改或者覆盖默认的转换器,就能达到json的转换的自定义
1.Fastjson2的官方对于springboot的支持
@Beanpublic FastJsonConfig fastJsonConfig() {//1.自定义配置...FastJsonConfig config = new FastJsonConfig();config.setDateFormat("yyyy-MM-dd HH:mm:ss");//2.1配置序列化的行为//JSONWriter.Feature.PrettyFormat:格式化输出config.setWriterFeatures(JSONWriter.Feature.PrettyFormat);//2.2配置反序列化的行为config.setReaderFeatures(JSONReader.Feature.FieldBased, JSONReader.Feature.SupportArrayToBean);return config;}/*** 使用 FastJsonHttpMessageConverter 来替换 Spring MVC 默认的 HttpMessageConverter* 以提高 @RestController @ResponseBody @RequestBody 注解的 JSON序列化和反序列化速度。* */@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> converters) {//1.转换器FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();converter.setDefaultCharset(StandardCharsets.UTF_8);converter.setFastJsonConfig(fastJsonConfig());converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));converters.add(0, converter);}....//详情请查看com.alibaba.fastjson2.JSONWebMvcConfigurer.java
文档地址:Fastjson2增强扩展
关于Fastjson2与Fastjson1的区别,请参考:
Fastjson1与Fastjson2的差别,深入简化的分析



