1. 问题背景与现象描述
最近在SpringBoot项目中集成FastJson2作为默认的JSON序列化组件时,遇到了一个关于日期类型序列化的棘手问题。当通过WebMvcConfigurer配置FastJsonHttpMessageConverter替换默认的Jackson时,发现Date类型并没有按照预期序列化为时间戳(毫秒数),而是变成了"yyyy-MM-dd HH:mm:ss"格式的字符串。
这个现象非常反直觉,因为直接使用FastJson2的API(如JSON.toJSONString())时,Date类型默认就是输出时间戳的。但在SpringMVC的MessageConverter环境下,这个默认行为却失效了。
2. 环境复现与问题定位
2.1 基础配置代码
先来看下典型的配置方式,这也是大多数开发者会采用的方案:
java复制@Configuration
public class FastJsonConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setDateFormat("millis"); // 关键配置
converter.setFastJsonConfig(config);
converter.setDefaultCharset(StandardCharsets.UTF_8);
converters.add(0, converter);
}
}
2.2 问题表现
配置了setDateFormat("millis")后,预期的行为应该是所有Date类型都序列化为时间戳。但实际测试发现:
- 直接调用`JS
