问题描述
在我们最近的项目中,我们使用java 8.我需要将java.time.LocalDateTime序列化为java脚本的日期格式。
In our recent project we use java 8. I need to serialize java.time.LocalDateTime to java script Date format.
目前我所做的是定义一个自定义序列化程序,将LocalDateTime转换为时间戳。
Currently what I did was define a custom serializer to convert LocalDateTime to timestamp.
public class LocalDateTimeSerializer implements JsonSerializer<LocalDateTime> {
@Override
public JsonElement serialize(LocalDateTime localDateTime, Type type, JsonSerializationContext jsonSerializationContext) {
Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
Date date = Date.from(instant);
return new JsonPrimitive(date.getTime());
}
}
然后使用GsonBuilder和我的自定义LocalDateTimeSerializer一起创建Gson对象
then create Gson object using GsonBuilder with my custom LocalDateTimeSerializer
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeSerializer());
Gson gson = gsonBuilder.create();
然后在Java Script中,我使用此时间戳创建一个Date对象。它工作正常。
Then in Java Script I create a Date object using this time stamp. It's working fine.
我需要知道,这种方式还行还是有更好的方法吗?
I need to know, is this way ok or is there a better way to do this?
推荐答案
是的,这是最好的方式。
YES, that's the best way.
强烈推荐将 Time
对象转换为它的 long
类型表示,当您要将它从一个系统转移到另一个系统时。这可以避免许多问题,例如数据格式化和不同系统中的本地时间。
It's highly recommended to convert a Time
object into it's long
type representation when you're going to transfer it from one system to another. This can avoid many problems, such as data formatting and time local in different systems.
而且, long
表示只需要8个字节,而字符串表示需要多一点。这意味着 long
表示传输和解析更有效。
And what's more, long
representation takes only 8 bytes, while string representation takes a little more. Which means long
representation is more efficient to transfer and parse.
这篇关于使用GSON将java.time.LocalDateTime(java 8)序列化为js Date的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!