SpringBoot2.0如何集成fastjson?在网上查了一堆资料,但是各文章的说法不一,有些还是错的,可能只是简单测试一下就认为ok了,最后有没生效都不知道。恰逢公司项目需要将JackSon换成fastjson,因此自己来实践一下SpringBoot2.0和fastjson的整合,同时记录下来方便自己后续查阅。

一、Maven依赖说明

    SpringBoot的版本为: <version>2.1.4.RELEASE</version>
    在pom文件中添加fastjson的依赖:
        <!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
6
 
1
        <!-- fastjson -->
2
        <dependency>
3
            <groupId>com.alibaba</groupId>
4
            <artifactId>fastjson</artifactId>
5
            <version>1.2.56</version>
6
        </dependency>


二、整合

        我们写一个配置类WebConfig实现WebMvcConfigurer接口,然后重写configureMessageConverters方法。具体的代码如下:
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);
}
}
65
 
1
package com.psx.gqxy.config;
2

3
import com.alibaba.fastjson.serializer.SerializerFeature;
4
import com.alibaba.fastjson.support.config.FastJsonConfig;
5
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
6
import org.springframework.context.annotation.Configuration;
7
import org.springframework.http.MediaType;
8
import org.springframework.http.converter.HttpMessageConverter;
9
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
10
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
11
import java.util.ArrayList;
12
import java.util.List;
13

14
/**
15
 * web相关的定制化配置
16
 * @author ZENG.XIAO.YAN
17
 * @version 1.0
18
 * @Date 9012-88-88
19
 */
20
@Configuration
21
public class WebConfig implements WebMvcConfigurer {
22
    // WebMvcConfigurerAdapter 这个类在SpringBoot2.0已过时,官方推荐直接实现WebMvcConfigurer 这个接口
23

24
    /**
25
     * 使用fastjson代替jackson
26
     * @param converters
27
     */
28
    @Override
29
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
30
        /*
31
         先把JackSon的消息转换器删除.
32
         备注: (1)源码分析可知,返回json的过程为:
33
                    Controller调用结束后返回一个数据对象,for循环遍历conventers,找到支持application/json的HttpMessageConverter,然后将返回的数据序列化成json。
34
                    具体参考org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor的writeWithMessageConverters方法
35
               (2)由于是list结构,我们添加的fastjson在最后。因此必须要将jackson的转换器删除,不然会先匹配上jackson,导致没使用fastjson
36
        */
37
        for (int i = converters.size() - 1; i >= 0; i--) {
38
            if (converters.get(i) instanceof MappingJackson2HttpMessageConverter) {
39
                converters.remove(i);
40
            }
41
        }
42
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
43

44
        //自定义fastjson配置
45
        FastJsonConfig config = new FastJsonConfig();
46
        config.setSerializerFeatures(
47
                SerializerFeature.WriteMapNullValue,        // 是否输出值为null的字段,默认为false,我们将它打开
48
                SerializerFeature.WriteNullListAsEmpty,     // 将Collection类型字段的字段空值输出为[]
49
                SerializerFeature.WriteNullStringAsEmpty,   // 将字符串类型字段的空值输出为空字符串
50
                SerializerFeature.WriteNullNumberAsZero,    // 将数值类型字段的空值输出为0
51
                SerializerFeature.WriteDateUseDateFormat,
52
                SerializerFeature.DisableCircularReferenceDetect    // 禁用循环引用
53
        );
54
        fastJsonHttpMessageConverter.setFastJsonConfig(config);
55

56
        // 添加支持的MediaTypes;不添加时默认为*/*,也就是默认支持全部
57
        // 但是MappingJackson2HttpMessageConverter里面支持的MediaTypes为application/json
58
        // 参考它的做法, fastjson也只添加application/json的MediaType
59
        List<MediaType> fastMediaTypes = new ArrayList<>();
60
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
61
        fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
62
        converters.add(fastJsonHttpMessageConverter);
63
    }
64
}
65



三、测试

        (1)代码
        要测试fastjson是否整合成功的话,我们只需要在实体类中使用一下fastjson的注解就ok。如果注解生效了,说明fastjson整合成功了。直接看代码
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;
}
}
49
 
1
package com.psx.gqxy.web.controller;
2

3
import com.alibaba.fastjson.annotation.JSONField;
4
import com.psx.gqxy.common.base.ModelResult;
5
import lombok.Data;
6
import org.springframework.web.bind.annotation.GetMapping;
7
import org.springframework.web.bind.annotation.RestController;
8
import java.util.Date;
9
import java.util.List;
10

11
/**
12
 * TestController
13
 * @author ZENG.XIAO.YAN
14
 * @version 1.0
15
 * @Date 9012-88-88
16
 */
17
@RestController
18
public class TestController {
19

20
    @GetMapping("/json")
21
    public ModelResult<JsonBean> testJson() {
22
        ModelResult<JsonBean> result = new ModelResult<>();
23
        JsonBean jsonBean = new JsonBean();
24
        jsonBean.setBirthDay(new Date());
25
        jsonBean.setName("测试");
26
        result.setData(jsonBean);
27
        // 效果
28
        /*{
29
            "code": "200",
30
                "data": {
31
            "birthDay": "2019年05月12日",
32
                    "name": "测试",
33
                    "qqList": []
34
        },
35
            "msg": ""
36
        }*/
37
        return result;
38
    }
39

40

41
    @Data
42
    class JsonBean {
43
        private String name;
44
        @JSONField(format = "yyyy年MM月dd日")
45
        private Date birthDay;
46
        private List<String> qqList;
47
    }
48
}
49

        (2)效果
                


        通过这个2步的测试,发现fastjson的注解生效了,也就说明整合成功了

四、杂谈

    SpringBoot2.0后,有些东西改变了。在SpringBoot 1.X时代,整合fastjson是可以不排除JackSon消息转换器的。但在SpringBoot2.X时代,必须要排除JackSon消息转换器。

            
 
 

SpringBoot2.0整合fastjson的正确姿势的更多相关文章

  1. 第二篇:SpringBoot2.0整合ActiveMQ

    本篇开始将具体介绍SpringBoot如何整合其它项目. 如何创建SpringBoot项目 访问https://start.spring.io/. 依次选择构建工具Maven Project.语言ja ...

  2. SpringBoot2.0 整合 QuartJob ,实现定时器实时管理

    一.QuartJob简介 1.一句话描述 Quartz是一个完全由java编写的开源作业调度框架,形式简易,功能强大. 2.核心API (1).Scheduler 代表一个 Quartz 的独立运行容 ...

  3. SpringBoot2.0 整合 Swagger2 ,构建接口管理界面

    一.Swagger2简介 1.Swagger2优点 整合到Spring Boot中,构建强大RESTful API文档.省去接口文档管理工作,修改代码,自动更新,Swagger2也提供了强大的页面测试 ...

  4. SpringBoot2.0 整合 Dubbo框架 ,实现RPC服务远程调用

    一.Dubbo框架简介 1.框架依赖 图例说明: 1)图中小方块 Protocol, Cluster, Proxy, Service, Container, Registry, Monitor 代表层 ...

  5. SpringBoot2.0 整合 Redis集群 ,实现消息队列场景

    本文源码:GitHub·点这里 || GitEE·点这里 一.Redis集群简介 1.RedisCluster概念 Redis的分布式解决方案,在3.0版本后推出的方案,有效地解决了Redis分布式的 ...

  6. springboot2.0整合logback日志(详细)

    <div class="post"> <h1 class="postTitle"> springboot2.0整合logback日志(详 ...

  7. Springboot2.0整合Redis(注解开发)

    一. pom.xm文件引入对应jar包 <dependency> <groupId>org.springframework.boot</groupId> <a ...

  8. springBoot2.0+redis+fastJson+自定义注解实现方法上添加过期时间

    springBoot2.0集成redis实例 一.首先引入项目依赖的maven jar包,主要包括 spring-boot-starter-data-redis包,这个再springBoot2.0之前 ...

  9. SpringBoot2.0应用(三):SpringBoot2.0整合RabbitMQ

    如何整合RabbitMQ 1.添加spring-boot-starter-amqp <dependency> <groupId>org.springframework.boot ...

随机推荐

  1. eth0: ERROR while getting interface flags: No such device的解决方法、Linux怎么修改IP以及ping不通的处理方法

    首先输入ifconfig命令查看当前的ip信息 发现没有eth0这个网卡设备,有ens33 接着输入命令:ifconfig ens33 192.168.2.110    --  修改临时ip地址,系统 ...

  2. VIJOS-P1234 口袋的天空

    洛谷 P1195 口袋的天空 https://www.luogu.org/problemnew/show/P1195 JDOJ 1374: VIJOS-P1234 口袋的天空 https://neoo ...

  3. Redis删除特定前缀key的优雅实现

    还在用keys命令模糊匹配删除数据吗?这就是一颗随时爆炸的炸弹! Redis中没有批量删除特定前缀key的指令,但我们往往需要根据前缀来删除,那么究竟该怎么做呢?可能你一通搜索后会得到下边的答案 re ...

  4. [THUPC2018]弗雷兹的玩具商店(线段树,背包)

    最近状态有点颓,刷刷水题找找自信. 首先每次询问就是完全背包.可以 $O(m^2)$. 由于每个物品都可以用无数次,所以对于价格相同的物品,我们只用考虑愉悦度最高的. 直接上线段树.$val[i]$ ...

  5. [LeetCode] 263. Ugly Number 丑陋数

    Write a program to check whether a given number is an ugly number. Ugly numbers are positive numbers ...

  6. 团队作业第五次—项目冲刺-Day4

    Day4 part1-SCRUM: 项目相关 作业相关 具体描述 所属班级 2019秋福大软件工程实践Z班 作业要求 团队作业第五次-项目冲刺 作业正文 hunter--冲刺集合 团队名称 hunte ...

  7. QLayout及其子类 清除添加的widget

    起初,我的思路是,先取得Layout的items数量, 然后通过索引来移除每一个items,代码如下: QHBoxLayout * hly = new QHBoxLayout; ; i < ; ...

  8. 2019.11.12&13题解

    写在前面: 虽然拿到了rk1,但是T3被卡常TLE90分,(考后再交就A了!?),lemon80,又丢失了一次良好的AK机会, 掐头去尾距离联赛仅剩2天,最近中午一直睡不好,可能是有些紧张, 希望自己 ...

  9. 【操作系统之十三】Netfilter与iptables

    一.Netfilter Netfilter是由Rusty Russell提出的Linux 2.4内核防火墙框架,该框架既简洁又灵活,可实现安全策略应用中的许多功能,如数据包过滤.数据包处理.地址伪装. ...

  10. python爬取电影网站信息

    一.爬取前提1)本地安装了mysql数据库 5.6版本2)安装了Python 2.7 二.爬取内容 电影名称.电影简介.电影图片.电影下载链接 三.爬取逻辑1)进入电影网列表页, 针对列表的html内 ...