我正在使用Kotlin 1.3.10 (并绑定到此版本)和0.13,而且我在中序列化地图时遇到了问题。
我有以下代码:
@Serializer(forClass = LocalDate::class)
object LocalDateSerializer : KSerializer<LocalDate> {
private val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
override val descriptor: SerialDescriptor
get() = StringDescriptor.withName("LocalDate")
override fun serialize(encoder: Encoder, obj: LocalDate) {
encoder.encodeString(obj.format(formatter))
}
override fun deserialize(decoder: Decoder): LocalDate {
return LocalDate.parse(decoder.decodeString(), formatter)
}
}
@Serializable
data class MyClass (
val students: Map<String,LocalDate>
)
@UnstableDefault
@Test
fun decodeEncodeSerialization() {
val jsonParser = Json(
JsonConfiguration(
allowStructuredMapKeys = true
)
)
val mc = MyClass(
mapOf("Alex" to LocalDate.of(1997,2,23))
)
val mcJson = jsonParser.stringify(MyClass.serializer(), mc)
val mcObject = jsonParser.parse(MyClass.serializer(), mcJson)
assert(true)
}
检查代码时有一条红线,上面写着“没有找到'LocalDate‘的序列化程序。要使用上下文序列化程序作为后盾,可以使用@ContextualSerialization显式注释类型或属性。”
对于其他类型的字段,添加@Serialization就足够了。
@Serializable
data class Student (
val name: String,
@Serializable(with = LocalDateSerializer::class)
val dob: LocalDate
)
但有了地图我似乎想不出是怎么回事。我把它放在上面或者物体旁边..。
@Serializable
data class MyClass (
val students: Map<String,@Serializable(with = LocalDateSerializer::class) LocalDate> //here
//or
//@Serializable(with = LocalDateSerializer::class)
//val students2: Map<String, LocalDate> //here
)
...but测试仍然失败
kotlinx.serialization.SerializationException:无法定位类java.time.LocalDate的非参数序列化程序(Kotlin反射不可用)。对于泛型类,如列表,请显式提供序列化程序。
我的解决办法是
@Serializable
data class MyClass (
val students: List<Student>
)
@Serializable
data class Student (
val name: String,
@Serializable(with = LocalDateSerializer::class)
val dob: LocalDate
)
有什么办法我不会求助于解决办法吗?谢谢!
发布于 2021-03-05 17:42:49
@file:UseSerializers(LocalDateSerializer::class)
将其放入对象声明的文件中,每次看到Local时都应该使用LocalDateSerializer
https://stackoverflow.com/questions/60813349
复制相似问题