Gson Converter For Java.Time LocalDateTime To ISO Date String (Kotlin)

April 13, 2018

Create the LocalDateTimeConverter class

class LocalDateTimeConverter : JsonSerializer<LocalDateTime>, JsonDeserializer<LocalDateTime> {

    override fun serialize(src: LocalDateTime?, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement? {
        return JsonPrimitive(FORMATTER.format(src))
    }

    override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): LocalDateTime? {
        return FORMATTER.parse(json!!.asString, LocalDateTime.FROM)
    }

    companion object {
        private val FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE_TIME
    }
}

Register the converter with registerTypeAdapter

val gson = GsonBuilder().registerTypeAdapter(LocalDateTime::class.java, LocalDateTimeConverter).create()

val now = LocalDateTime.now(ZoneOffset.UTC)

val jsonString = gson.toJson(now)
// Output: 2018-04-10T03:45:26.009

val newNow = gson.fromJson<LocalDateTime>(jsonString, LocalDateTime::class.java)
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.