Kotlin / kotlinx-datetime

KotlinX multiplatform date/time library
Apache License 2.0
2.42k stars 101 forks source link

Introduce serializers corresponding to custom formats #350

Open dkhalanskyjb opened 8 months ago

dkhalanskyjb commented 8 months ago

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>.

morki commented 8 months ago

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

dkhalanskyjb commented 8 months ago

@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))
    }

}
morki commented 8 months ago

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?,
)