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. 为什么Audition CC2017扫描不了电音插件,你需要这个工具

    一时兴起,我也去下载并安装了Audition的音频后期处理软件,版本是cc2017.简单熟悉了对自己声音修理外,我还想添加一点电音的效果显得洋气一些.在网上下载并安装了warves tune后,发现A ...

  2. 一步一步实现kbmmw的httpsys使用https功能

    kbmmw的httpsys的功能已经实现了好长时间,但是现在各个平台都要求使用https来提供服务. 今天一步一步来说一下如何使用kbmmw 的httpsys功能支持https. 首先为了获得证书,我 ...

  3. Kubernetes架构及相关服务详解

    11.1.了解架构 K8s分为两部分: 1.Master节点 2.node节点 Master节点组件: 1.etcd分布式持久化存储 2.api服务器 3.scheduler 4.controller ...

  4. 拖拽插件SortableJS

    在项目中,经常会遇到一些涉及到拖拽的需求,github上面有一个开源的SortableJS的插件,支持Vue,React,Angular等多种框架,实现效果很好,基本可以满足大部分的需求,下面就第一次 ...

  5. 金生芳-实验十四 团队项目评审&课程学习总结

    实验十四 团队项目评审&课程学习总结 项目 内容 这个作业属于哪个课程 [教师博客主页链接] 这个作业的要求在哪里 [作业链接地址] 作业学习目标 (1)掌握软件项目评审会流程(2)反思总结课 ...

  6. 项目Beta冲刺--2/7

    项目Beta冲刺--2/7 作业要求 这个作业属于哪个课程 软件工程1916-W(福州大学) 这个作业要求在哪里 项目Beta冲刺 团队名称 基于云的胜利冲锋队 项目名称 云评:高校学生成绩综合评估及 ...

  7. Java 并发,相关术语

    Java 并发,相关术语: 术语 作用 synchronize 可修饰方法.代码块.类:介绍:https://www.cnblogs.com/zyxiaohuihui/p/9096882.html L ...

  8. Python 类的继承__init__() takes exactly 3 arguments (1 given)

    类(class),可以继承基类以便形成具有自己独特属性的类,我们在面向对象的编程中,经常用到类及其继承,可以说没有什么不是类的,今天我们就来详细探讨一下在python中,类的继承是如何做的. 我们假设 ...

  9. windows使用 xxx.bat运行相关指令

    今日思语:成人的世界,请停止低层次的忙碌 一般是windows上需要执行一些支持的命令时,我们一般都会直接使用控制台去操作,对于需要频繁操作的指令来说,使用控制台略显有些不便,比如不小心关闭后控制台后 ...

  10. PHP - Filters

    Retrieve the administrator password of this application. 对文件包含的介绍------------第一个链接需要谷歌 https://mediu ...