LocalDateTime与时间戳转换的全局配置

问题

在开发中,我们使用LocalDateTime为时间类型作为返回给前端,或者接收给前端的值,经常遇到返回变成了这种形式。

json 复制代码
{
	"timestamp": [
		2024,
		1,
		12,
		16,
		36,
		29,
		592604100
	]
}

所以我们需要规定一种统一格式来进行接收与返回,我采用的时间戳的形式

json 复制代码
{
	"timestamp": 1705048744521
}

解决方案

java 复制代码
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, new JsonLocalDateTimeSupport.LocalDateTimeSerializer());
        javaTimeModule.addDeserializer(LocalDateTime.class, new JsonLocalDateTimeSupport.LocalDateTimeDeserializer());
        ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().modules(javaTimeModule).build();
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(objectMapper);
        converters.add(0, converter);
    }
}

在上述代码中添加了LocalDateTimed的时间戳序列化以及反序列化,用于返回给前端时间戳,或是接收前端传来的时间戳,所以我们需要实现这两个序列化方法

java 复制代码
public interface JsonLocalDateTimeSupport {
    // 序列化实现
    class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
        @Override
        public void serialize(LocalDateTime localDateTime, JsonGenerator gen, SerializerProvider serializers)
                throws IOException {
            if (localDateTime != null) {
                long timestamp = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
                gen.writeNumber(timestamp);
            }
        }
    }

    // 反序列化实现
    class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
        @Override
        public LocalDateTime deserialize(JsonParser p, DeserializationContext deserializationContext)
                throws IOException {
            long timestamp = p.getValueAsLong();
            if (timestamp > 0) {
                return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
            } else {
                return null;
            }
        }
    }
}

配置完上述代码后即可实现LocalDateTime与时间戳转换的全局配置

相关推荐
学长毕业设计3 小时前
基于SpringBoot的公益基金管理系统(源码+文档+讲解视频)
java·spring boot·后端
东小西4 小时前
【SAA实战】第 3 篇 · 工具调用全攻略:把业务能力交给 Agent 自己调度
java·后端·spring
东小西4 小时前
【SAA实战】第 4 篇 · Agent 短期记忆:saver 让 Agent 跨轮记得住(threadId 隔离)
java·后端·spring
许彰午4 小时前
22-DataCenter报文序列化
java·低代码·架构·状态模式
2601_962065254 小时前
[MySQL] SQL优化之性能分析
java·sql·mysql
小范同学_4 小时前
JDK1.7 与 JDK1.8 HashMap 底层原理对比 + 数组并发扩容死循环详解
java·开发语言
予昊5 小时前
从零实现“在线五子棋对战“:WebSocket 实时通信 + 段位匹配
java·开发语言·网络·websocket
2601_962203515 小时前
【SpringAI入门】初识SpringAI
java
weixin_461408586 小时前
Mybatis-flex小记
java·开发语言·mybatis
2601_962177136 小时前
【MySQL篇】聚合查询,联合查询
android·java·mysql