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

Apr 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.009val newNow = gson.fromJson<LocalDateTime>(jsonString, LocalDateTime::class.java)

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.