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

相关推荐
布朗克1685 分钟前
Java 10 新特性及具体应用
java·开发语言·新特性·java10
ZZHow10243 小时前
JavaWeb开发_Day05
java·笔记·web
CHEN5_023 小时前
【Java虚拟机】垃圾回收机制
java·开发语言·jvm
Warren983 小时前
Lua 脚本在 Redis 中的应用
java·前端·网络·vue.js·redis·junit·lua
艾伦~耶格尔7 小时前
【数据结构进阶】
java·开发语言·数据结构·学习·面试
爪洼传承人7 小时前
18- 网络编程
java·网络编程
smileNicky8 小时前
SpringBoot系列之从繁琐配置到一键启动之旅
java·spring boot·后端
祈祷苍天赐我java之术8 小时前
Java 迭代器(Iterator)详解
java·开发语言
David爱编程8 小时前
为什么必须学并发编程?一文带你看懂从单线程到多线程的演进史
java·后端
我命由我123458 小时前
软件开发 - 避免过多的 if-else 语句(使用策略模式、使用映射表、使用枚举、使用函数式编程)
java·开发语言·javascript·设计模式·java-ee·策略模式·js