You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 2.3版本升级后如何全局配置java.sql.Timestamp返回毫秒格式

问题原因

Spring Boot 2.x 版本调整了Jackson序列化的默认规则,默认关闭了WRITE_DATES_AS_TIMESTAMPS特性,所以java.sql.Timestamp、java.util.Date等时间类型都会被序列化为ISO 8601格式的字符串,和1.x版本的默认行为不同。

全局配置方案(无需修改POJO)

方案1:通过配置文件直接修改(最简单)

直接在项目的application.properties或application.yml中添加以下配置即可:

application.properties 写法

# 开启时间类型序列化为时间戳
spring.jackson.serialization.write-dates-as-timestamps=true
# 可选:设置时区,避免时间偏移问题,和你业务所用时区保持一致即可
spring.jackson.time-zone=GMT+8

application.yml 写法

spring:
  jackson:
    serialization:
      write-dates-as-timestamps: true
    time-zone: GMT+8

方案2:通过Jackson自定义配置类实现(适配复杂场景)

如果你的项目有自定义的ObjectMapper配置,或者需要只针对Timestamp类型单独做时间戳序列化(不影响其他时间类型的序列化规则),可以添加如下配置类:

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.sql.Timestamp;

@Configuration
public class JacksonTimestampConfig {

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer timestampSerializerCustomizer() {
        return builder -> builder
                // 仅针对Timestamp类型序列化为毫秒时间戳
                .serializerByType(Timestamp.class, new JsonSerializer<Timestamp>() {
                    @Override
                    public void serialize(Timestamp timestamp, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                        jsonGenerator.writeNumber(timestamp.getTime());
                    }
                });
    }
}
注意事项

如果项目中存在手动声明的ObjectMapper Bean,需要在该Bean的初始化逻辑中手动开启WRITE_DATES_AS_TIMESTAMPS特性,或者注入上述自定义的序列化规则,否则自动配置的规则会被自定义的ObjectMapper覆盖。

内容的提问来源于stack exchange,提问作者user3250123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 10:18:03