To further amplify @Nicholas Terry answer:
You might also need a serializer:
String dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
GSON gson = new GsonBuilder()
.registerTypeAdapter(
LocalDateTime.class,
(JsonDeserializer<LocalDateTime>) (json, type, jsonDeserializationContext) ->
ZonedDateTime.parse(json.getAsJsonPrimitive().getAsString()).toLocalDateTime()
)
.registerTypeAdapter(
LocalDateTime.class,
(JsonSerializer<LocalDateTime>) (localDate, type, jsonSerializationContext) ->
new JsonPrimitive(formatter.format(localDate)
)
.create();
Or the kotlin version:
val dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
val formatter = DateTimeFormatter.ofPattern(dateFormat)
val gson: Gson = GsonBuilder()
.registerTypeAdapter(
LocalDateTime::class.java,
JsonDeserializer { json, type, jsonDeserializationContext ->
ZonedDateTime.parse(json.asJsonPrimitive.asString).toLocalDateTime()
} as JsonDeserializer<LocalDateTime?>
)
.registerTypeAdapter(
LocalDateTime::class.java,
JsonSerializer<LocalDateTime?> { localDate, type, jsonDeserializationContext ->
JsonPrimitive(formatter.format(localDate))
}
)
.create()