kotlinx-datetime icon indicating copy to clipboard operation
kotlinx-datetime copied to clipboard

Introduce serializers corresponding to custom formats

Open dkhalanskyjb opened this issue 1 year ago • 3 comments

Right now, we provide serializers that format the entities of our library as ISO 8601 strings, using toString and parse functions. However, now that parse and format can work with custom formats, we could provide things like class LocalDateCustomSerializer(format: DateTimeFormat<LocalDate>): KSerializer<LocalDate>.

dkhalanskyjb avatar Feb 29 '24 12:02 dkhalanskyjb

This will resolve so much pain we are facing now, thank you! :)

morki avatar Mar 06 '24 08:03 morki

@morki, if you're truly in pain, as a workaround, you can introduce simple pieces of code like this in the meantime:

public class LocalDateCustomSerializer(private val format: DateTimeFormat<LocalDate>): KSerializer<LocalDate> {

    override val descriptor: SerialDescriptor =
        PrimitiveSerialDescriptor("kotlinx.datetime.LocalDate", PrimitiveKind.STRING)

    override fun deserialize(decoder: Decoder): LocalDate =
        LocalDate.parse(decoder.decodeString(), format)

    override fun serialize(encoder: Encoder, value: LocalDate) {
        encoder.encodeString(value.format(format))
    }

}

dkhalanskyjb avatar Mar 06 '24 13:03 dkhalanskyjb

Thank you very much! :)

I did't know it will be so easy, we have been deserializing in custom getters from string for custom formats so far and it was a pain.

For others, here is how to use it in serializable class:

object SlovakLocalDateSerializer : LocalDateCustomSerializer(LocalDate.Format {
    dayOfMonth(Padding.NONE)
    char('.')
    optional { char(' ') }
    monthNumber(Padding.NONE)
    char('.')
    optional { char(' ') }
    year(Padding.NONE)
})

@Serializable
data class Example(
    @Serializable(with = SlovakLocalDateSerializer::class)
    val exampleDate: LocalDate?,
)

morki avatar Mar 06 '24 13:03 morki