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)