SpringBoot2.0整合fastjson的正确姿势
一、Maven依赖说明
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
二、整合
package com.psx.gqxy.config;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.List;
/**
* web相关的定制化配置
* @author ZENG.XIAO.YAN
* @version 1.0
* @Date 9012-88-88
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
// WebMvcConfigurerAdapter 这个类在SpringBoot2.0已过时,官方推荐直接实现WebMvcConfigurer 这个接口
/**
* 使用fastjson代替jackson
* @param converters
*/
@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 fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
//自定义fastjson配置
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(
SerializerFeature.WriteMapNullValue, // 是否输出值为null的字段,默认为false,我们将它打开
SerializerFeature.WriteNullListAsEmpty, // 将Collection类型字段的字段空值输出为[]
SerializerFeature.WriteNullStringAsEmpty, // 将字符串类型字段的空值输出为空字符串
SerializerFeature.WriteNullNumberAsZero, // 将数值类型字段的空值输出为0
SerializerFeature.WriteDateUseDateFormat,
SerializerFeature.DisableCircularReferenceDetect // 禁用循环引用
);
fastJsonHttpMessageConverter.setFastJsonConfig(config);
// 添加支持的MediaTypes;不添加时默认为*/*,也就是默认支持全部
// 但是MappingJackson2HttpMessageConverter里面支持的MediaTypes为application/json
// 参考它的做法, fastjson也只添加application/json的MediaType
List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
converters.add(fastJsonHttpMessageConverter);
}
}
package com.psx.gqxy.config;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.List;
/**
* web相关的定制化配置
* @author ZENG.XIAO.YAN
* @version 1.0
* @Date 9012-88-88
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
// WebMvcConfigurerAdapter 这个类在SpringBoot2.0已过时,官方推荐直接实现WebMvcConfigurer 这个接口
/**
* 使用fastjson代替jackson
* @param converters
*/
@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 fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
//自定义fastjson配置
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(
SerializerFeature.WriteMapNullValue, // 是否输出值为null的字段,默认为false,我们将它打开
SerializerFeature.WriteNullListAsEmpty, // 将Collection类型字段的字段空值输出为[]
SerializerFeature.WriteNullStringAsEmpty, // 将字符串类型字段的空值输出为空字符串
SerializerFeature.WriteNullNumberAsZero, // 将数值类型字段的空值输出为0
SerializerFeature.WriteDateUseDateFormat,
SerializerFeature.DisableCircularReferenceDetect // 禁用循环引用
);
fastJsonHttpMessageConverter.setFastJsonConfig(config);
// 添加支持的MediaTypes;不添加时默认为*/*,也就是默认支持全部
// 但是MappingJackson2HttpMessageConverter里面支持的MediaTypes为application/json
// 参考它的做法, fastjson也只添加application/json的MediaType
List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
converters.add(fastJsonHttpMessageConverter);
}
}
三、测试
package com.psx.gqxy.web.controller;
import com.alibaba.fastjson.annotation.JSONField;
import com.psx.gqxy.common.base.ModelResult;
import lombok.Data;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.List;
/**
* TestController
* @author ZENG.XIAO.YAN
* @version 1.0
* @Date 9012-88-88
*/
@RestController
public class TestController {
@GetMapping("/json")
public ModelResult<JsonBean> testJson() {
ModelResult<JsonBean> result = new ModelResult<>();
JsonBean jsonBean = new JsonBean();
jsonBean.setBirthDay(new Date());
jsonBean.setName("测试");
result.setData(jsonBean);
// 效果
/*{
"code": "200",
"data": {
"birthDay": "2019年05月12日",
"name": "测试",
"qqList": []
},
"msg": ""
}*/
return result;
}
@Data
class JsonBean {
private String name;
@JSONField(format = "yyyy年MM月dd日")
private Date birthDay;
private List<String> qqList;
}
}
package com.psx.gqxy.web.controller;
import com.alibaba.fastjson.annotation.JSONField;
import com.psx.gqxy.common.base.ModelResult;
import lombok.Data;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.List;
/**
* TestController
* @author ZENG.XIAO.YAN
* @version 1.0
* @Date 9012-88-88
*/
@RestController
public class TestController {
@GetMapping("/json")
public ModelResult<JsonBean> testJson() {
ModelResult<JsonBean> result = new ModelResult<>();
JsonBean jsonBean = new JsonBean();
jsonBean.setBirthDay(new Date());
jsonBean.setName("测试");
result.setData(jsonBean);
// 效果
/*{
"code": "200",
"data": {
"birthDay": "2019年05月12日",
"name": "测试",
"qqList": []
},
"msg": ""
}*/
return result;
}
@Data
class JsonBean {
private String name;
@JSONField(format = "yyyy年MM月dd日")
private Date birthDay;
private List<String> qqList;
}
}

四、杂谈
SpringBoot2.0整合fastjson的正确姿势的更多相关文章
- 第二篇:SpringBoot2.0整合ActiveMQ
本篇开始将具体介绍SpringBoot如何整合其它项目. 如何创建SpringBoot项目 访问https://start.spring.io/. 依次选择构建工具Maven Project.语言ja ...
- SpringBoot2.0 整合 QuartJob ,实现定时器实时管理
一.QuartJob简介 1.一句话描述 Quartz是一个完全由java编写的开源作业调度框架,形式简易,功能强大. 2.核心API (1).Scheduler 代表一个 Quartz 的独立运行容 ...
- SpringBoot2.0 整合 Swagger2 ,构建接口管理界面
一.Swagger2简介 1.Swagger2优点 整合到Spring Boot中,构建强大RESTful API文档.省去接口文档管理工作,修改代码,自动更新,Swagger2也提供了强大的页面测试 ...
- SpringBoot2.0 整合 Dubbo框架 ,实现RPC服务远程调用
一.Dubbo框架简介 1.框架依赖 图例说明: 1)图中小方块 Protocol, Cluster, Proxy, Service, Container, Registry, Monitor 代表层 ...
- SpringBoot2.0 整合 Redis集群 ,实现消息队列场景
本文源码:GitHub·点这里 || GitEE·点这里 一.Redis集群简介 1.RedisCluster概念 Redis的分布式解决方案,在3.0版本后推出的方案,有效地解决了Redis分布式的 ...
- springboot2.0整合logback日志(详细)
<div class="post"> <h1 class="postTitle"> springboot2.0整合logback日志(详 ...
- Springboot2.0整合Redis(注解开发)
一. pom.xm文件引入对应jar包 <dependency> <groupId>org.springframework.boot</groupId> <a ...
- springBoot2.0+redis+fastJson+自定义注解实现方法上添加过期时间
springBoot2.0集成redis实例 一.首先引入项目依赖的maven jar包,主要包括 spring-boot-starter-data-redis包,这个再springBoot2.0之前 ...
- SpringBoot2.0应用(三):SpringBoot2.0整合RabbitMQ
如何整合RabbitMQ 1.添加spring-boot-starter-amqp <dependency> <groupId>org.springframework.boot ...
随机推荐
- redis常用命令手册大全
一.五种数据类型1.Redis字符串StringString 是最简单的类型,你可以理解成与 Memcached 是一模一样的类型,一个 key 对应一个value,其上支持的操作与 Memcache ...
- COSO企业风险管理框架及其在大宗商品行业的应用
https://mp.weixin.qq.com/s/P1NDvqsz0GNObm1pb47mfg 中国期货市场交易量领先全球,期权.互换等新的衍生品工具逐步引入,场外衍生品服务商正在涌现.越来越多的 ...
- Media Formatters(媒体格式化器)
6.1.1 Internet的媒体类型 媒体类型,也叫做MIME类型,标识了数据的格式.在HTTP中,媒体类型描述了消息体的格式.一个媒体类型由两个字符串组成:类型和子类型.例如: text/html ...
- HTML基础五-starrysky页面动起来
Starrysky前端框架 链接:https://pan.baidu.com/s/1P8mPrHZjyRtzw1NWnAx-9w 提取码:cjl5 接口文档:https://www.showdoc.c ...
- Java的十三个设计模式
OOP三大基本特性 封装 封装,也就是把客观事物封装成抽象的类,并且类可以把自己的属性和方法只让可信的类操作,对不可信的进行信息隐藏. 继承 继承是指这样一种能力,它可以使用现有的类的所有功能,并在无 ...
- Apex 中 DML 进阶知识小结
DML 选项 在 DML 语句执行的时候可以设置选项.这些选项用 DML.Options 类来表示. 完整的介绍在官方文档中. 在建立一个 DML.Options 实例之后,可以使用 setOptio ...
- 3.Vue的基本语法
1.v-bind 可简写为":" 你看到的 v-bind 等被称为指令.指令带有前缀 v-,以表示它们是 Vue 提供的特殊特性. 我们可以使用 v-bind 来绑定元素特性! 在 ...
- 【2019.7.25 NOIP模拟赛 T1】变换(change)(思维+大分类讨论)
几个性质 我们通过推式子可以发现: \[B⇒AC⇒AAB⇒AAAC⇒C\] \[C⇒AB⇒AAC⇒AAAB⇒B\] 也就是说: 性质一: \(B,C\)可以相互转换. 则我们再次推式子可以发现: \[ ...
- 日常笔记4关于cin、cin.get()、cin.getline()、getline()使用区别
1.关于PAT中段错误 使用字符数组出现错误: char str[256]; 报错段错误,然后改用C++中的string 改成: string str; 同char数组一样,也可以使用下标来取单个字符 ...
- Python爬虫爬取数据的步骤
爬虫: 网络爬虫是捜索引擎抓取系统(Baidu.Google等)的重要组成部分.主要目的是将互联网上的网页下载到本地,形成一个互联网内容的镜像备份. 步骤: 第一步:获取网页链接 1.观察需要爬取的多 ...