虚拟主机管理怎么做网站,界面设计包括哪三个方面,国际化网站建设,室内装修设计在哪里学问题
在开发中#xff0c;我们使用LocalDateTime为时间类型作为返回给前端#xff0c;或者接收给前端的值#xff0c;经常遇到返回变成了这种形式。
{timestamp: [2024,1,12,16,36,29,592604100]
}所以我们需要规定一种统一格式来进行接收与返回#xff0c;我…问题
在开发中我们使用LocalDateTime为时间类型作为返回给前端或者接收给前端的值经常遇到返回变成了这种形式。
{timestamp: [2024,1,12,16,36,29,592604100]
}所以我们需要规定一种统一格式来进行接收与返回我采用的时间戳的形式
{timestamp: 1705048744521
}解决方案
Configuration
public class WebConfig implements WebMvcConfigurer {Overridepublic void extendMessageConverters(ListHttpMessageConverter? 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的时间戳序列化以及反序列化用于返回给前端时间戳或是接收前端传来的时间戳所以我们需要实现这两个序列化方法
public interface JsonLocalDateTimeSupport {// 序列化实现class LocalDateTimeSerializer extends JsonSerializerLocalDateTime {Overridepublic 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 JsonDeserializerLocalDateTime {Overridepublic 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与时间戳转换的全局配置