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与时间戳转换的全局配置

相关推荐
7哥♡ۣۖᝰꫛꫀꪝۣℋ10 分钟前
Spring-cloud\Eureka
java·spring·微服务·eureka
老毛肚22 分钟前
手写mybatis
java·数据库·mybatis
两点王爷25 分钟前
Java基础面试题——【Java语言特性】
java·开发语言
choke23329 分钟前
[特殊字符] Python 文件与路径操作
java·前端·javascript
choke23334 分钟前
Python 基础语法精讲:数据类型、运算符与输入输出
java·linux·服务器
岁岁种桃花儿1 小时前
CentOS7 彻底卸载所有JDK/JRE + 重新安装JDK8(实操完整版,解决kafka/jps报错)
java·开发语言·kafka
roman_日积跬步-终至千里1 小时前
【Java并发】Java 线程池实战:警惕使用CompletableFuture.supplyAsync
java·开发语言·网络
毕设源码-钟学长1 小时前
【开题答辩全过程】以 基于Springboot的扶贫众筹平台为例,包含答辩的问题和答案
java·spring boot·后端
CodeSheep程序羊2 小时前
拼多多春节加班工资曝光,没几个敢给这个数的。
java·c语言·开发语言·c++·python·程序人生·职场和发展
我是咸鱼不闲呀2 小时前
力扣Hot100系列19(Java)——[动态规划]总结(上)(爬楼梯,杨辉三角,打家劫舍,完全平方数,零钱兑换)
java·leetcode·动态规划