Open dkhalanskyjb opened 8 months ago
This will resolve so much pain we are facing now, thank you! :)
@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))
}
}
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?,
)
Right now, we provide serializers that format the entities of our library as ISO 8601 strings, using
toString
andparse
functions. However, now thatparse
andformat
can work with custom formats, we could provide things likeclass LocalDateCustomSerializer(format: DateTimeFormat<LocalDate>): KSerializer<LocalDate>
.