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 共存的

相关推荐
lulu121654407815 分钟前
OpenRouter Fusion 多模型融合架构深度拆解:预算级模型组团打平 Fable 5,多模型协作才是 AGI 的正确打开方式?
java·人工智能·架构·ai编程·agi
雨辰AI20 分钟前
生产级实测:SpringBoot3 + 达梦数据库接口从 200ms 优化至 20ms 完整调优指南
java·数据库·spring boot·后端·政务
(Charon)1 小时前
【C++ 面试高频:内存管理、RAII 和智能指针详解】
java·开发语言·word
凡人叶枫1 小时前
Effective C++ 条款39:明智而审慎地使用 private 继承
java·数据库·c++·嵌入式开发
轻刀快马1 小时前
跨越软硬件的共鸣(二):从 Cache 写策略看 Redis 与 DB 的一致性博弈
java·开发语言·redis·计算机组成原理
折哥的程序人生 · 物流技术专研1 小时前
Java 23 种设计模式:从踩坑到精通 | 装饰器模式 —— 比继承更灵活的扩展方式,你用过吗?
java·装饰器模式·java面试·结构型模式·java设计模式·javaio·从踩坑到精通
lili00122 小时前
2026 企业 AI 选型新范式:OpenRouter Fusion 证明多模型融合性价比远超单模型,企业该如何重构技术栈? - 微元算力(weytoken)
java·人工智能·python·重构·ai编程
shushangyun_2 小时前
汽车服务行业B2B平台+AI解决方案哪家专业:2026年最新测评
java·运维·网络·数据库·人工智能·汽车
A.说学逗唱的Coke2 小时前
【大模型专题】Spring AI Alibaba × Skill 整合实战:让 AI 真正“会干活
java·人工智能·spring
大黄说说2 小时前
深入理解 Go 协程 Goroutine:并发编程的核心精髓
java·数据库·python