Spring MVC 将 Jackson 序列化器替换为 FastJson2 序列化器
·
项目版本与运行环境
- JDK 版本:17
- 操作系统:Windows 11
- SpringBoot 版本:3.5.14
引入依赖
<!-- FastJson2 核心 -->
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.61</version>
</dependency>
<!-- FastJson2 - Spring 集成 -->
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2-extension-spring6</artifactId>
<version>2.0.61</version>
</dependency>
编写配置
/**
* Spring MVC 配置类
*
*/
@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {
/**
* 自定义消息转换器
*
* @param converters 消息转换器列表
*/
@Override
public void configureMessageConverters(@NonNull List<HttpMessageConverter<?>> converters) {
// 将 FastJson2 放置在列表第一位
converters.add(0, createFastJsonConverter());
}
public static FastJsonHttpMessageConverter createFastJsonConverter() {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setCharset(StandardCharsets.UTF_8);
// 序列化配置
config.setWriterFeatures(
JSONWriter.Feature.WriteLongAsString, // Long → String 防精度丢失
JSONWriter.Feature.WriteMapNullValue // 输出 null 字段(按需)
);
// 反序列化配置
config.setReaderFeatures(
// 反序列化时忽略未知字段,避免报错
);
converter.setFastJsonConfig(config);
// 设置默认字符集为 UTF-8,避免中文乱码
converter.setDefaultCharset(StandardCharsets.UTF_8);
// 限定转换器仅处理 application/json 媒体类型
converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));
return converter;
}
}
测试配置是否生效
编写测试类
@GetMapping("/test/json")
public Map<String, Object> testJson() {
Map<String, Object> result = new HashMap<>();
result.put("id", 9007199254740993L); // 超出 JS 安全整数范围
result.put("name", null); // null 字段
result.put("time",LocalDateTime.now());
return result;
}
Fastjson2 默认的日期序列化格式与 Jackson 不同。返回一个包含 LocalDateTime / Date 的对象,对比格式:
Jackson: 默认 ISO-8601 (“2026-06-25T20:09:00”) 或时间戳
Fastjson2: 默认 “yyyy-MM-dd HH:mm:ss” 格式
输出信息为:
{
"id":"9007199254740993",
"name":null,
"time":"2026-06-25 20:15:33"
}
由输出信息可看出,已使用 FastJson2 序列化器。
更多推荐



所有评论(0)