Fastjson 默認序列化 Date 為時間戳 (長整型),前端需手動格式化。期望直接輸出 yyyy-MM-dd HH:mm:ss 等可讀格式。
優點:精確控制單字段,無全局副作用
缺點:字段多時重複代碼
public class User {
private Long id;
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
@JSONField(format = "yyyy-MM-dd")
private Date birthday;
// getter/setter
}
通過自定義 HttpMessageConverter 統一設置日期格式。
public class CustomFastJsonHttpMessageConverter extends FastJsonHttpMessageConverter {
public CustomFastJsonHttpMessageConverter() {
FastJsonConfig config = new FastJsonConfig();
// 核心:設置日期格式
config.setDateFormat("yyyy-MM-dd HH:mm:ss");
// 推薦的序列化特性
config.setSerializerFeatures(
SerializerFeature.PrettyFormat,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.DisableCircularReferenceDetect
);
config.setCharset(StandardCharsets.UTF_8);
setFastJsonConfig(config);
// 設置支持的 MediaType
List<MediaType> mediaTypes = new ArrayList<>();
mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
mediaTypes.add(MediaType.APPLICATION_JSON);
setSupportedMediaTypes(mediaTypes);
}
}
<!-- spring-mvc.xml -->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<!-- 替換默認的 FastJsonHttpMessageConverter -->
<bean class="com.yourpkg.util.CustomFastJsonHttpMessageConverter">
<property name="features">
<list>
<value>WriteDateUseDateFormat</value> <!-- 關鍵:使用 dateFormat 格式化日期 -->
<value>WriteMapNullValue</value>
<value>QuoteFieldNames</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// 1. 創建自定義轉換器
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
// 2. 配置
FastJsonConfig config = new FastJsonConfig();
config.setDateFormat("yyyy-MM-dd HH:mm:ss");
config.setSerializerFeatures(
SerializerFeature.WriteDateUseDateFormat, // 必須開啟!
SerializerFeature.PrettyFormat,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.DisableCircularReferenceDetect
);
config.setCharset(StandardCharsets.UTF_8);
converter.setFastJsonConfig(config);
// 3. 設置 MediaType
converter.setSupportedMediaTypes(Arrays.asList(
MediaType.APPLICATION_JSON_UTF8,
MediaType.APPLICATION_JSON
));
// 4. 添加到首位 (優先使用)
converters.add(0, converter);
}
}
必須開啟此特性,setDateFormat 才會生效。否則仍輸出時間戳。
| 配置 | 作用 |
|---|---|
| config.setDateFormat("yyyy-MM-dd HH:mm:ss") | 定義日期格式模板 |
| SerializerFeature.WriteDateUseDateFormat | 啟用上述格式輸出日期 |
| JSON.DEFAULT_DATE_FORMAT | 全局靜態設置 (不推薦,線程不安全) |
Fastjson 自動支持多種格式解析,無需額外配置:
// 以下格式均可自動解析為 Date
"2024-03-15 14:30:00"
"2024-03-15"
"2024/03/15 14:30:00"
1709994600000 // 時間戳毫秒數
如需嚴格限定格式,可在字段加 @JSONField(format = "yyyy-MM-dd HH:mm:ss", deserializeUsing = CustomDeserializer.class)。
Fastjson 1.2.30+ 支持 LocalDateTime、LocalDate、LocalTime,需額外依賴:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
<!-- Java 8 時間模塊 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson-extension</artifactId>
<version>1.2.83</version>
</dependency>
配置:
FastJsonConfig config = new FastJsonConfig();
// Java 8 時間格式化
config.setDateFormat("yyyy-MM-dd HH:mm:ss"); // 對 Date 生效
// LocalDateTime 等使用 JSON.toJSONString(obj, SerializerFeature.WriteClassName)
// 或自定義 ValueFilter 處理
| 現象 | 原因 | 解決 |
|---|---|---|
| 仍輸出時間戳 | 未開啟 WriteDateUseDateFormat | config.setSerializerFeatures(WriteDateUseDateFormat) |
| 日期少 8 小時 | 時區問題 (UTC vs GMT+8) | config.setTimeZone(TimeZone.getTimeZone("GMT+8")) 或 JVM -Duser.timezone=GMT+8 |
| 配置不生效 | 轉換器順序靠後,Jackson 先處理 | converters.add(0, converter) 放首位 |
| 中文亂碼 | 編碼未設置 UTF-8 | config.setCharset(StandardCharsets.UTF_8) |
Spring MVC 整合 Fastjson 日期格式化核心:自定義 FastJsonHttpMessageConverter → 設置 dateFormat + WriteDateUseDateFormat → 註冊到 MessageConverters 首位。字段級別用 @JSONField,全局用配置類。Spring Boot 項目用 WebMvcConfigurer 方式最簡潔。