【问题标题】:Is there a way to serialize a map in Kotlinx-Serialization有没有办法在 Kotlinx-Serialization 中序列化地图
【发布时间】:2020-03-23 12:12:46
【问题描述】:

我正在使用 Kotlin 1.3.10(并绑定到此版本)和 Kotlinx-Serialization 0.13,但在 Kotlinx-Serialization 中序列化地图时遇到问题。

我有以下代码:

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

...但测试仍然失败

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
)

有没有办法我不会求助于解决方法?谢谢!

【问题讨论】:

    标签: java dictionary kotlin serialization


    【解决方案1】:
    @file:UseSerializers(LocalDateSerializer::class)
    

    把它放在你的对象被声明的文件中,它应该在每次看到本地日期时使用 LocalDateSerializer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多