javajsonserializationgson

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


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?


Solution

  • 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.