Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce serializers corresponding to custom formats #350

Open
dkhalanskyjb opened this issue Feb 29, 2024 · 3 comments
Open

Introduce serializers corresponding to custom formats #350

dkhalanskyjb opened this issue Feb 29, 2024 · 3 comments
Labels
formatters Related to parsing and formatting
Milestone

Comments

@dkhalanskyjb
Copy link
Contributor

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 dkhalanskyjb added the formatters Related to parsing and formatting label Feb 29, 2024
@morki
Copy link

morki commented Mar 6, 2024

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

@dkhalanskyjb
Copy link
Contributor Author

@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
Copy link

morki commented Mar 6, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
formatters Related to parsing and formatting
Projects
None yet
Development

No branches or pull requests

2 participants