Are there standard serializers for java.time types...
# serialization
j
Are there standard serializers for java.time types i.e LocalTime, LocalDate, Instant, etc..? Does such a thing exist. The idea being that they can be imported into a project so that Kotlinx serialization can serialize java.time types automatically?
e
kotlinx.serialization is multiplatform and java.time is JVM-only, so it doesn't come built-in
it's not completely obvious what format to choose for them, either - ISO-8601 strings may make sense for most JSON APIs, but maybe millis as Long for protobuf
👍🏾 1
you can define your own
Copy code
object LocalDateSerializer : KSerializer<LocalDate> {
    override val descriptor: SerialDescriptor =
        PrimitiveSerialDescriptor("LocalDateSerializer", PrimitiveKind.STRING)
    override fun serialize(encoder: Encoder, value: LocalDate) {
        encoder.encodeString(DateTimeFormatter.ISO_DATE.format(value))
    }
    override fun deserialize(decoder: Decoder): LocalDate =
        LocalDate.parse(decoder.decodeString())
}
etc. pretty easily, and
@file:UseSerializaers(LocalDateSerializer::class, ...)
at the top of files where you define your serializable data types that use
java.time.*
you could also convert to kotlinx.datetime which is multiplatform (doesn't depend on java.time.*) and documented to have ISO-8601 serializers
j
Thanks @ephemient
158 Views