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

相关推荐
BillKu1 小时前
Java + Spring Boot + Mybatis 实现批量插入
java·spring boot·mybatis
YuTaoShao1 小时前
Java八股文——集合「Map篇」
java
有梦想的攻城狮3 小时前
maven中的maven-antrun-plugin插件详解
java·maven·插件·antrun
硅的褶皱7 小时前
对比分析LinkedBlockingQueue和SynchronousQueue
java·并发编程
MoFe17 小时前
【.net core】天地图坐标转换为高德地图坐标(WGS84 坐标转 GCJ02 坐标)
java·前端·.netcore
季鸢8 小时前
Java设计模式之观察者模式详解
java·观察者模式·设计模式
Fanxt_Ja8 小时前
【JVM】三色标记法原理
java·开发语言·jvm·算法
Mr Aokey8 小时前
Spring MVC参数绑定终极手册:单&多参/对象/集合/JSON/文件上传精讲
java·后端·spring
小马爱记录9 小时前
sentinel规则持久化
java·spring cloud·sentinel
长勺10 小时前
Spring中@Primary注解的作用与使用
java·后端·spring