Kotlin: How do I serialize LocalDateTime using kotlinx serializer?
Asked Answered
S

1

6

How would I go about serializing LocalDateTime using kotlinx serializer

I've read that I would need to include implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.4.0") in my dependencies, which I did, but I'm still getting this error:

Serializer has not been found for type 'LocalDateTime'. To use context serializer as fallback, explicitly annotate type or property with @Contextual

Is there something else I should also imported in the same script?

Thanks for your time.

Shaven answered 28/3, 2023 at 6:8 Comment(1)
Importing the kotlinx-datetime library is not enough; you have to use the types from that library, instead of java.time, as the kotlinx-datetime types are annotated with the appropriate @Serializable annotations. If you wish to continue using the java.time types directly, then you'll need to create your own serializers. See this related Q&A. It none of this helps solve your problem then please provide a minimal reproducible example.Brockwell
W
8

You can create your own serializer model, using:

Imports:

import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.Serializer
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
@Serializer(forClass = LocalDate::class)
object DateSerializer : KSerializer<LocalDate> {
    private val formatter = DateTimeFormatter.ISO_LOCAL_DATE

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

    override fun deserialize(decoder: Decoder): LocalDate {
        return LocalDate.parse(decoder.decodeString(), formatter)
    }
}

And then use a @Serializabe class describer, for example:

    @Serializable(with = DateSerializer::class)
    val startDate: LocalDate,
    @Serializable(with = DateSerializer::class)
    val endDate: LocalDate
Withers answered 13/10, 2023 at 13:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.