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的两种实现方法:

  1. 实现WebMvcConfigurer接口的void configureMessageConverters(List<HttpMessageConverter<?>> converters)方法;
  2. 在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的更多相关文章

  1. Unity 游戏框架搭建 2019 (四十六) 简易消息机制 & 集成到 MonoBehaviourSimplify 里

    在上一篇,我们接触了单例,使用单例解决了我们脚本之间访问的问题. 脚本之间访问其实有更好的方式. 我们先分下脚本访问脚本的几种形式. 第一种,A GameObject 是 B GameObject 的 ...

  2. SpringBoot(十六)_springboot整合JasperReport6.6.0

    现在项目上要求实现套打,结果公司里有个人建议用JaperReport进行实现,就进入这个东西的坑中.好歹经过挣扎现在已经脱离此坑中.现在我也是仅能实现读取数据库数据转成pdf进行展示,包括中文的展示. ...

  3. Jmeter(二十六)Jmeter-Question之“集成Jenkins”

    Jenkins,最初被称为Hudson,是一个Java语言编写的开源持续集成工具.Jenkins在持续集成领域的市场份额居于主导地位,其被各种规模的团队用于各种语言和技术的项目中,比如.net.rub ...

  4. springboot(十六)-swagger2

    SpringBoot整合Swagger2 相信各位在公司写API文档数量应该不少,当然如果你还处在自己一个人开发前后台的年代,当我没说,如今为了前后台更好的对接,还是为了以后交接方便,都有要求写API ...

  5. springboot(十六):使用Jenkins部署Spring Boot

    jenkins是devops神器,本篇文章介绍如何安装和使用jenkins部署Spring Boot项目 jenkins搭建 部署分为三个步骤: 第一步,jenkins安装 第二步,插件安装和配置 第 ...

  6. springboot(十六):springboot整合shiro

    数据库有五张表(userInfo,uerrole,role,rolepermission,permission) userInfo(id,username,password) userrole(uid ...

  7. 第十六节: EF的CodeFirst模式通过Fluent API修改默认协定

    一. 简介 1. 优先级:Fluent API > data annotations > default conventions. 2. 所有的Fluent API配置都要在 OnMode ...

  8. 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的无状态模 ...

  9. SpringBoot | 第二十六章:邮件发送

    前言 讲解了日志相关的知识点后.今天来点相对简单的,一般上,我们在开发一些注册功能.发送验证码或者订单服务时,都会通过短信或者邮件的方式通知消费者,注册或者订单的相关信息.而且基本上邮件的内容都是模版 ...

随机推荐

  1. Vue.js前端MVVM框架实战篇

    相信大家对vue.js这个前端框架有了一定的了解.想必也想把Vue急切的运用在项目中,看看它的魅力到底有多大?别急,今天我会满足大家的想法. 我们一起来看看“Webpack+Vue”的开发模式相比以往 ...

  2. JavaScript的函数call和apply的区别、以及bind方法

    1.call和apply的定义和区别 call和apply的作用一样,唯一不同的是:接受的参数不同. apply:方法能够劫持另一个对象的方法,继承另一个对象的属性. Funciton.apply(o ...

  3. android中listview滑动卡顿的原因

    导致Android界面滑动卡顿主要有两个原因: 1.UI线程(main)有耗时操作 2.视图渲染时间过长,导致卡顿 http://www.tuicool.com/articles/fm2IFfU 

  4. springboot使用阿里fastjson来解析数据

    1.spring boot默认使用的json解析框架是jackson,使用fastjson需要配置,首先引入fastjson依赖 pom.xml配置如下: <project xmlns=&quo ...

  5. Junit测试。

    Junit使用: 白盒测试 步骤: 1.定义测试类. 2.定义测试方法:可以单独运行. 3.给方法加@Test,导入junit依赖环境. 判定结果: 红色:失败  绿色:成功. 一般不看输出,而是使用 ...

  6. Prometheus学习笔记(2)Prometheus部署

    目录 Prometheus的安装配置启动 Prometheus的安装配置启动 1.Prometheus二进制安装 Prometheus下载链接:https://prometheus.io/downlo ...

  7. angular8 配置 测试环境打包指令 生成测试环境包指令

    1.angular.json 文件中在architect 下添加 buildTest指令 距离位置 projects => (你的项目名称) => architect 下和 build 指 ...

  8. 转:spring mvc 设置@Scope("prototype")

    spring中bean的scope属性,有如下5种类型: singleton 表示在spring容器中的单例,通过spring容器获得该bean时总是返回唯一的实例prototype表示每次获得bea ...

  9. iView学习笔记(三):表格搜索,过滤及隐藏列操作

    iView学习笔记(三):表格搜索,过滤及隐藏某列操作 1.后端准备工作 环境说明 python版本:3.6.6 Django版本:1.11.8 数据库:MariaDB 5.5.60 新建Django ...

  10. 2019年杭电多校第二场 1012题Longest Subarray(HDU6602+线段树)

    题目链接 传送门 题意 要你找一个最长的区间使得区间内每一个数出现次数都大于等于\(K\). 思路 我们通过固定右端点考虑每个左端点的情况. 首先对于每个位置,我们用线段树来维护它作为\(C\)种元素 ...