Kotlin:如何使用kotlinx serializer序列化LocalDateTime?

nxagd54h  于 2023-10-23  发布在  Kotlin
关注(0)|答案(1)|浏览(177)

如何使用kotlinx serializer序列化LocalDateTime
我已经读到我需要在我的依赖项中包含implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.4.0"),我做到了,但我仍然得到这个错误:
Serializer has not been found for type 'LocalDateTime'. To use context serializer as fallback, explicitly annotate type or property with @Contextual
在同一脚本中是否还需要导入其他内容?
谢谢你的时间。

mfuanj7w

mfuanj7w1#

你可以创建你自己的序列化器模型,使用:
进口:

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)
    }
}

然后使用@Serializabe类描述符,例如:

@Serializable(with = DateSerializer::class)
    val startDate: LocalDate,
    @Serializable(with = DateSerializer::class)
    val endDate: LocalDate

相关问题