首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring MVC 整合 Fastjson 實現日期時間格式化完整方案

     編輯:Java 相關知識

場景痛點

Fastjson 默認序列化 Date 為時間戳 (長整型),前端需手動格式化。期望直接輸出 yyyy-MM-dd HH:mm:ss 等可讀格式。

方案一:實體類字段級別控制 (@JSONField)

優點:精確控制單字段,無全局副作用
缺點:字段多時重複代碼


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
}

方案二:全局配置 FastJsonHttpMessageConverter (推薦)

通過自定義 HttpMessageConverter 統一設置日期格式。

1. 自定義轉換器類


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);
    }
}

2. Spring MVC XML 配置註冊


<!-- 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>

3. Spring Boot Java Config 方式 (現代項目推薦)


@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);
    }
}

關鍵特性:WriteDateUseDateFormat

必須開啟此特性,setDateFormat 才會生效。否則仍輸出時間戳。

配置作用
config.setDateFormat("yyyy-MM-dd HH:mm:ss")定義日期格式模板
SerializerFeature.WriteDateUseDateFormat啟用上述格式輸出日期
JSON.DEFAULT_DATE_FORMAT全局靜態設置 (不推薦,線程不安全)

反序列化:前端傳日期字符串 → Date

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)。

Java 8 时间類型支持

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 處理

常見問題排查

現象原因解決
仍輸出時間戳未開啟 WriteDateUseDateFormatconfig.setSerializerFeatures(WriteDateUseDateFormat)
日期少 8 小時時區問題 (UTC vs GMT+8)config.setTimeZone(TimeZone.getTimeZone("GMT+8")) 或 JVM -Duser.timezone=GMT+8
配置不生效轉換器順序靠後,Jackson 先處理converters.add(0, converter) 放首位
中文亂碼編碼未設置 UTF-8config.setCharset(StandardCharsets.UTF_8)

總結

Spring MVC 整合 Fastjson 日期格式化核心:自定義 FastJsonHttpMessageConverter → 設置 dateFormat + WriteDateUseDateFormat → 註冊到 MessageConverters 首位。字段級別用 @JSONField,全局用配置類。Spring Boot 項目用 WebMvcConfigurer 方式最簡潔。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved