Serializer has not been found for type 'LocalDate'
Asked Answered
C

1

5

I am just trying to create serializable values but i am getting the following error;

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

My code is pretty simple;

import kotlinx.serialization.Serializable
import java.time.LocalDate

Serializable
data class ProviderData(
    val provider: String,
    @Contextual 
    val serviceStartDate: LocalDate,
    @Contextual 
    val serviceEndDate: LocalDate
)

What should I do to be able to user Date, or LocalDate types?

Cohette answered 29/8, 2023 at 16:41 Comment(0)
E
6

The @Contextual annotation is used to indicate that the property is serialized and deserialized using a contextual serializer, which is especially useful for types like LocalDate that require custom serialization logic.

U need to make first class which convert LocalData.

@Serializer(forClass = LocalDate::class)
class LocalDateSerializer : KSerializer<LocalDate> {
    private val formatter: DateTimeFormatter = 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)
    }
}

Next you need add to your data class serializer @Serializable instead @Contextual like here:

@Serializable
data class ProviderData(
    val provider: String,
    @Serializable(with = LocalDateSerializer::class)
    val serviceStartDate: LocalDate,
    @Serializable(with = LocalDateSerializer::class)
    val serviceEndDate: LocalDate
)

You can make it with data, LocalDataTime, like you want.

Emmett answered 29/8, 2023 at 17:17 Comment(1)
It would make more sense to serialize LocalDates to epoch time as a Long. No need to do complex String manipulation into a human-readable format.Babette

© 2022 - 2024 — McMap. All rights reserved.