Best practice to Serialize java.time.LocalDateTime (java 8) to js Date using GSON

旧街凉风 提交于 2019-12-30 03:58:07

问题


In our recent project we use java 8. I need to serialize java.time.LocalDateTime to java script Date format.

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());
    }
}

then create Gson object using GsonBuilder with my custom LocalDateTimeSerializer

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeSerializer());

Gson gson = gsonBuilder.create();

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?


回答1:


YES, that's the best way.

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.

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.




回答2:


Java 8 solution from LocalDateTime to Epoch Milliseconds or Seconds:

// to Epoch Seconds
long sec = localDateTime.toInstant(ZoneOffset.UTC).getEpochSecond();

// to Epoch Milliseconds
long msec = localDateTime.toInstant(ZoneOffset.UTC).toEpochMilli();

In your case however I see a bug which uses Local Timezone instead of UTC. My recommended solution would be:

@Override
public JsonElement serialize(LocalDateTime localDateTime, Type type, JsonSerializationContext jsonSerializationContext) {
    long sec = localDateTime.toInstant(ZoneOffset.UTC).getEpochSecond();
    return new JsonPrimitive(sec);
}


来源:https://stackoverflow.com/questions/21981902/best-practice-to-serialize-java-time-localdatetime-java-8-to-js-date-using-gso

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!