Spring Boot 配置 FastJson

jackson

Spring Boot 自带的序列化工具是 jackson

最简单使用

java 复制代码
@RestController  
public class PingController {  
    @GetMapping("ping")  
    public Map<String, Object> ping() {  
        Map<String, Object> map = new HashMap<>();  
        Date date = new Date();
        map.put("data", "pong");  
        map.put("date", date)
        return map;  
    }  
}

配置 jackson 序列行为

yaml 复制代码
spring:  
  jackson:  
    date-format: yyyy-MM-dd HH:mm:ss  # 时间格式化方式  
    time-zone: Asia/Shanghai  # 时区  
    serialization:  
      write-dates-as-timestamps: false # 时间戳

响应结果:

json 复制代码
{
	"date": "2024-10-13 13:55:16",
	"data": "pong"
}

fastjson

Spring Boot 3.x 中配置 fastjson

安装依赖

gradle 复制代码
implementation "com.alibaba:fastjson:1.2.83"

配置 fastjson 有三种:

  1. 利用 Spring Boot 自动配置机制配置
  2. 使用 @EnableWebMvc 注解,Spring Boot 自动配置机制会失效
  3. 使用 FastJsonHttpMessageConverter 替换 jackson

使用 Spring Boot 自动配置机制

java 复制代码
@Configuration  
public class WebConfig implements WebMvcConfigurer {  
    @Bean  
    public FastJsonConfig fastJsonConfig() {  
        FastJsonConfig config = new FastJsonConfig();  
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");  // 时间格式化
        config.setSerializerFeatures(SerializerFeature.PrettyFormat); // 美化输出
        config.setSerializeConfig(SerializeConfig.globalInstance);   // 表示开启全局序列化配置
        return config;  
    }  
  
    @Override  
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {  
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();  
        converter.setDefaultCharset(StandardCharsets.UTF_8);  // 设置字符集为 UTF-8   
        List<MediaType> mediaTypes = Collections.singletonList(MediaType.APPLICATION_JSON);  
        fastConverter.setSupportedMediaTypes(mediaTypes);  // 转换器只处理 application/json 类型的请求和响应
        fastConverter.setFastJsonConfig(fastJsonConfig());  
	    converters.add(0, fastConverter);  // 将 fastjson 转换器转换器添加到首位,确保优先使用 fastjson 转换器
    }
}

使用 @EnableWebMvc 注解

java 复制代码
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {  
    @Bean  
    public FastJsonConfig fastJsonConfig() {  
        FastJsonConfig config = new FastJsonConfig();  
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");  // 时间格式化
        config.setSerializerFeatures(SerializerFeature.PrettyFormat);  
        config.setSerializeConfig(SerializeConfig.globalInstance);  
        return config;  
    }  
  
    @Override  
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {  
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();  
        fastConverter.setDefaultCharset(StandardCharsets.UTF_8);  // 设置字符集为 UTF-8   
        List<MediaType> mediaTypes = Collections.singletonList(MediaType.APPLICATION_JSON);  
        fastConverter.setSupportedMediaTypes(mediaTypes);  // 转换器只处理 application/json 类型的请求和响应
        fastConverter.setFastJsonConfig(fastJsonConfig());  
	    converters.add(fastConverter);  // fastjson 会被添加到转换器列表的末尾,需要配置 EnableWebMvc 使用
    }
}

这两方式的区别就在于使用 converters.add(converter) 会将 fastjson 转换器添加到转换器列表的末尾,Spring Boot 内置的 jackson 转换器会优先执行

所以需要在类上面添加上 @EnableWebMvc 的注解,让 Spring Boot 内置的转换器失效

使用 FastJsonHttpMessageConverter 替换 jackson

java 复制代码
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Bean
    public FastJsonHttpMessageConverter responseBodyConverter() {
        FastJsonConfig config = new FastJsonConfig();
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");
        config.setSerializerFeatures(SerializerFeature.PrettyFormat);
        config.setSerializeConfig(SerializeConfig.globalInstance);
          
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        fastConverter.setFastJsonConfig(config);
        return fastConverter;
    }
}

与前面两种方式的区别是,这种方式是完全替代 jackson ,而前两种方式是 jacksonfastjson 共存的

相关推荐
武子康1 小时前
Java-80 深入浅出 RPC Dubbo 动态服务降级:从雪崩防护到配置中心秒级生效
java·分布式·后端·spring·微服务·rpc·dubbo
YuTaoShao4 小时前
【LeetCode 热题 100】131. 分割回文串——回溯
java·算法·leetcode·深度优先
源码_V_saaskw4 小时前
JAVA图文短视频交友+自营商城系统源码支持小程序+Android+IOS+H5
java·微信小程序·小程序·uni-app·音视频·交友
超浪的晨4 小时前
Java UDP 通信详解:从基础到实战,彻底掌握无连接网络编程
java·开发语言·后端·学习·个人开发
双力臂4045 小时前
Spring Boot 单元测试进阶:JUnit5 + Mock测试与切片测试实战及覆盖率报告生成
java·spring boot·后端·单元测试
Edingbrugh.南空5 小时前
Aerospike与Redis深度对比:从架构到性能的全方位解析
java·开发语言·spring
QQ_4376643146 小时前
C++11 右值引用 Lambda 表达式
java·开发语言·c++
永卿0016 小时前
设计模式-迭代器模式
java·设计模式·迭代器模式
誰能久伴不乏6 小时前
Linux如何执行系统调用及高效执行系统调用:深入浅出的解析
java·服务器·前端
itLaity6 小时前
基于Kafka实现简单的延时队列
spring boot·分布式·kafka