Search code examples
kotlinserialization

Serializer has not been found for type 'LocalDate'


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?


Solution

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