简体   繁体   English

Kotlin 实现密封接口的值 class 的序列化

[英]Kotlin serialization of value class that implements a sealed interface

I am trying to use Kotlin serialization (Kotlin 1.7.2, kotlinx.serialization 1.4.1) for value classes that implement a sealed interface:我正在尝试对实现密封接口的值类使用 Kotlin 序列化(Kotlin 1.7.2、kotlinx.serialization 1.4.1):

@Serializable
sealed interface Power {
    val value: Int
}

@Serializable
@JvmInline
value class PowerWatt(override val value: Int) : Power

@Serializable
@JvmInline
value class PowerHp(override val value: Int) : Power

When attempting serialization to Json, like so:尝试序列化为 Json 时,如下所示:

    @Test
    fun `Correctly serialize and deserialize a value class that implements a sealed interface`() {
        val power: Power = PowerWatt(123)
        val powerSerialized = Json.encodeToString(power)
        val powerDeserialized = Json.decodeFromString<Power>(powerSerialized)
        assertEquals(power, powerDeserialized)
    }

I run into the following error:我遇到以下错误:

kotlinx.serialization.json.internal.JsonDecodingException: Expected class kotlinx.serialization.json.JsonObject as the serialized body of Power, but had class kotlinx.serialization.json.JsonLiteral

    at kotlinx.serialization.json.internal.JsonExceptionsKt.JsonDecodingException(JsonExceptions.kt:24)
    at kotlinx.serialization.json.internal.PolymorphicKt.decodeSerializableValuePolymorphic(Polymorphic.kt:94)
    at kotlinx.serialization.json.internal.StreamingJsonDecoder.decodeSerializableValue(StreamingJsonDecoder.kt:81)
    at kotlinx.serialization.json.Json.decodeFromString(Json.kt:95)

How to make this work?如何使这项工作? Am I missing something?我错过了什么吗?

The answer was provided in a Kotlin Serialization GitHub Issue here .答案在此处的 Kotlin 序列化 GitHub 问题中提供。 For value classes, the wrapped underlying type is serialized directly.对于值类,包装的底层类型直接序列化。 Hence, there is not wrapping JSON object where the type field for the polymorphic serializer could be inserted.因此,没有包装 JSON object 可以插入多态序列化程序的type字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM