SpringBoot(十六):SpringBoot2.1.1集成fastjson,并使用fastjson替代默认的MappingJackson
springboot2.1.1默认采用的json converter是MappingJackson,通过调试springboot项目中代码可以确定这点。在springboot项目中定义WebMvcConfig.java
@Configuration
@Import({WebMvcAutoConfiguration.class})
@ComponentScan(
value = "com.dx.test.web",
includeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION, value = Controller.class)
})
public class WebMvcConfig implements WebMvcConfigurer {
/**
* 使用 fastjson 代替 jackson
*
* @param converters
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
List<HttpMessageConverter<?>> myConverters = converters;
}
}
断电设置在"List<HttpMessageConverter<?>> myConverters = converters;"这行代码处,然后调试进入该出断电,查看converters集合下元素:

从上表调试截图,可以发现springboot2.1.1默认采用的json converter是MappingJackson。
新建SpringBoot项目,并引入fastjson:
pom.xml配置如下:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <dependencies>
<!-- springboot web组件依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency> <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
SpringBoot入口类:
package com.dx.test.app; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; /**
* Hello world!
*/
@SpringBootApplication(scanBasePackages = {"com.dx.test"})
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
使用fastjson作为springboot2.x的json converter的两种实现方法:
- 实现WebMvcConfigurer接口的void configureMessageConverters(List<HttpMessageConverter<?>> converters)方法;
- 在WebMvcConfigurer接口实现类内定义bean(HttpMessageConverters)
为什么要使用fastjson替换jackson呢?
1)fastjson快;
2)国产,支持国产。
实现WebMvcConfigurer接口来使用fastjson:
实现代码如下:
/**
* WebMvcConfigurerAdapter 这个类在SpringBoot2.0已过时,官方推荐直接实现 WebMvcConfigurer 这个接口
*/
@Configuration
@Import({WebMvcAutoConfiguration.class})
@ComponentScan(
value = "com.dx.test.web",
includeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION, value = Controller.class)
})
public class WebMvcConfig implements 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);
}
}
实现思路,先把jackson从converters中移除掉,然后加入fastjson converter。
注意:
1)在该fastjson converter注入时,设置了fastjson配置信息:FastJsonConfig.setSerializerFeatures(循环依赖,是否输出null的字段等),这些设置将会影响Restful Api输出信息。
2)但是这个设置并不会影响系统JSON.toJSONString(List<Article>)的配置信息,如果需要控制序列化配置,需要这么使用:
// 序列化为json
String content = JSON.toJSONString(orderByItems, SerializerFeature.WriteMapNullValue);
在WebMvcConfigurer接口实现类内定义bean(HttpMessageConverters)来使用fastjson:
实现代码如下:
/**
* WebMvcConfigurerAdapter 这个类在SpringBoot2.0已过时,官方推荐直接实现 WebMvcConfigurer 这个接口
*/
@Configuration
@Import({WebMvcAutoConfiguration.class})
@ComponentScan(
value = "com.dx.test.web",
includeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION, value = Controller.class)
})
public class WebMvcConfig implements WebMvcConfigurer {
/**
* +支持fastjson的HttpMessageConverter
*
* @return HttpMessageConverters
*/
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
AbstractHttpMessageConverter abstractHttpMessageConverter = null;
//1.需要定义一个convert转换消息的对象;
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); //2:添加fastJson的配置信息;
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteDateUseDateFormat,
SerializerFeature.DisableCircularReferenceDetect);
fastJsonConfig.setCharset(Charset.forName("utf-8")); //3处理中文乱码问题
List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); //4.在convert中添加配置信息.
fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig); HttpMessageConverter<?> converter = fastJsonHttpMessageConverter; return new HttpMessageConverters(converter);
}
}
该方式会自动覆盖(替换jackson converter)。
针对json输出字段处理:格式化日期&控制字段是否输出:
1)日期格式化输出设置:只需要在实体的属性上添加注解@JSONField(format = "yyyy-MM-dd")
public class MyVo {
...
@JSONField(format = "yyyy-MM-dd")
@ApiModelProperty(value = "最新StartTime,不存在时,返回null")
private Date lastStartTimePlus1Day;// 最新startTime
/**
* @return the lastStartTimePlus1Day
*/
public Date getLastStartTimePlus1Day() {
return lastStartTimePlus1Day;
}
/**
* @param lastStartTimePlus1Day the lastStartTimePlus1Day to set
*/
public void setLastStartTimePlus1Day(Date lastStartTimePlus1Day) {
this.lastStartTimePlus1Day = lastStartTimePlus1Day;
}
}
2)控制字段是否输出,添加注解
public class MyVo{
...
@JSONField(serialize = true)
@ApiModelProperty("权重排序:仅排序使用,序列化不输出")
private Double weight;
/**
* @return the weight
*/
public Double getWeight() {
return weight;
}
/**
* @param weight the weight to set
*/
public void setWeight(Double weight) {
this.weight = weight;
}
}
SpringBoot(十六):SpringBoot2.1.1集成fastjson,并使用fastjson替代默认的MappingJackson的更多相关文章
- Unity 游戏框架搭建 2019 (四十六) 简易消息机制 & 集成到 MonoBehaviourSimplify 里
在上一篇,我们接触了单例,使用单例解决了我们脚本之间访问的问题. 脚本之间访问其实有更好的方式. 我们先分下脚本访问脚本的几种形式. 第一种,A GameObject 是 B GameObject 的 ...
- SpringBoot(十六)_springboot整合JasperReport6.6.0
现在项目上要求实现套打,结果公司里有个人建议用JaperReport进行实现,就进入这个东西的坑中.好歹经过挣扎现在已经脱离此坑中.现在我也是仅能实现读取数据库数据转成pdf进行展示,包括中文的展示. ...
- Jmeter(二十六)Jmeter-Question之“集成Jenkins”
Jenkins,最初被称为Hudson,是一个Java语言编写的开源持续集成工具.Jenkins在持续集成领域的市场份额居于主导地位,其被各种规模的团队用于各种语言和技术的项目中,比如.net.rub ...
- springboot(十六)-swagger2
SpringBoot整合Swagger2 相信各位在公司写API文档数量应该不少,当然如果你还处在自己一个人开发前后台的年代,当我没说,如今为了前后台更好的对接,还是为了以后交接方便,都有要求写API ...
- springboot(十六):使用Jenkins部署Spring Boot
jenkins是devops神器,本篇文章介绍如何安装和使用jenkins部署Spring Boot项目 jenkins搭建 部署分为三个步骤: 第一步,jenkins安装 第二步,插件安装和配置 第 ...
- springboot(十六):springboot整合shiro
数据库有五张表(userInfo,uerrole,role,rolepermission,permission) userInfo(id,username,password) userrole(uid ...
- 第十六节: EF的CodeFirst模式通过Fluent API修改默认协定
一. 简介 1. 优先级:Fluent API > data annotations > default conventions. 2. 所有的Fluent API配置都要在 OnMode ...
- ASP.NET MVC深入浅出系列(持续更新) ORM系列之Entity FrameWork详解(持续更新) 第十六节:语法总结(3)(C#6.0和C#7.0新语法) 第三节:深度剖析各类数据结构(Array、List、Queue、Stack)及线程安全问题和yeild关键字 各种通讯连接方式 设计模式篇 第十二节: 总结Quartz.Net几种部署模式(IIS、Exe、服务部署【借
ASP.NET MVC深入浅出系列(持续更新) 一. ASP.NET体系 从事.Net开发以来,最先接触的Web开发框架是Asp.Net WebForm,该框架高度封装,为了隐藏Http的无状态模 ...
- SpringBoot | 第二十六章:邮件发送
前言 讲解了日志相关的知识点后.今天来点相对简单的,一般上,我们在开发一些注册功能.发送验证码或者订单服务时,都会通过短信或者邮件的方式通知消费者,注册或者订单的相关信息.而且基本上邮件的内容都是模版 ...
随机推荐
- AMD规范中模块id的命名规则
AMD 即 Asynchronous Module Definition, 中文是“ 异步模块定义”的意思. AMD 规范制定了定义模块的规则,这样模块和模块的依赖可以被异步加载. AMD 规范只定义 ...
- Windows - CMD窗口UTF8编码乱码问题的解决!
问题描述 用MS-DOC打开 UTF-8 的文件时, 显示乱码问题根源 CMD默认是Windows系统默认编码(GBK), 用GBK格式来解码UTF-8的文件当然会出现乱码.解决方案 ...
- Java实现简易聊天室
Java实现简易聊天室 在学习<Java从入门到精通>这本书,网络通信,基于TCP实现的简易聊天室,我这里对书中的代码略做了修改,做个记录. 这里先放一下运行效果图,代码放在最后. 运行效 ...
- 微信小程序 子组件调用父组件方法
原文连接 ---> https://blog.csdn.net/qq_40190624/article/details/87972265 组件 js: var value = 123; ...
- go中如何更好的迭代
三种迭代方式 3 ways to iterate in Go 有如下三种迭代的写法: 回调函数方式迭代 通过Next()方法迭代.参照python 迭代器的概念,自定义Next()方法来迭代 通过ch ...
- C语言 dlopen dlsym
C语言加载动态库 头文件:#include<dlfcn.h> void * dlopen(const char* pathName, int mode); 返回值 handle void ...
- oVirt部署
所有前提建议: 关闭防火墙.selinux,配置hosts,计算机名使用域名 ovirt-engine部署 yum install http://resources.ovirt.org/pub/yum ...
- Elasticsearch 概念理解
官方文档地址 Filebeat: https://www.elastic.co/cn/products/beats/filebeat https://www.elastic.co/guide/en/b ...
- 201671010404+陈润菊 实验十四 团队项目评审课程&学习总结
个人学习总结博客 这个作业属于哪个课程 软件工程任教教师 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p/11093584.html 作业学习目标 (1 ...
- appuploader 使用
mac 使用 Jar Lanucher.app 打开 解压后的 appuploader.jar 文件,即可启动 appuploader. 内容 网址 官方网站 http://www.appupload ...