Java 8 LocalDateTime deserialized using Gson

The error occurs when you are deserializing the LocalDateTime attribute because GSON fails to parse the value of the attribute as it’s not aware of the LocalDateTime objects.

Use GsonBuilder’s registerTypeAdapter method to define the custom LocalDateTime adapter.
Following code snippet will help you to deserialize the LocalDateTime attribute.

Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
    @Override
    public LocalDateTime deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        Instant instant = Instant.ofEpochMilli(json.getAsJsonPrimitive().getAsLong());
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }
}).create();

Leave a Comment