Kotlin 序列化忽略字段

问题描述 投票:0回答:1

我正在尝试将

kotlinx.serialization
与 Atlas Device SDK 结合起来。我的想法是,我将使用 kotlin 序列化一个字段(
type
),第二个字段将使用 Atlas SDK
(_type
)保存到数据库中。因此,在
type
的设置器中,我总是将值设置为
_type
。 但是当我尝试测试序列化时,看起来
_type
设置不正确。反序列化可以忽略
type
setter 吗?

测试

@Test
fun testClassTest() {
    val dialogValue = TestClass(type = HeaderDialogValueType.DECIMAL_NUMBER)
    val dialogValueString = KotlinUtils.json.encodeToString(dialogValue)
    println(dialogValueString)
    val dialogValue2 = KotlinUtils.json.decodeFromString<HeaderDialogValue>(dialogValueString)

    assert(dialogValue.type == dialogValue2.type)
}

我想用Atlas SDK序列化并保存的类

@Serializable
class TestClass() {
    @Transient
    private var _type: String = HeaderDialogValueType.TEXT.name

    var type: HeaderDialogValueType = HeaderDialogValueType.TEXT
        get() {
            return HeaderDialogValueType.valueOf(_type)
        }
        set(value) {
            field = value
            _type = value.name
        }

    constructor(type: HeaderDialogValueType) : this() {
        this.type = type
    }
}

枚举类

@Serializable
enum class HeaderDialogValueType {
    @SerialName("NUMBER")
    NUMBER,
    @SerialName("TEXT")
    TEXT,
    @SerialName("ROLL")
    ROLL,
    @SerialName("DECIMAL_NUMBER")
    DECIMAL_NUMBER
}
kotlin serialization enums
1个回答
0
投票

确保您从正确的包中导入了 Transient 注释:

  • import kotlinx.serialization.Transient

我认为

KotlinUtils.json
kotlinx.serialization.json.Json
。如果是 GSON,您可能需要使用
@Expose(serialize = false)

还有,

decodeFromString<HeaderDialogValue>(...)
应该是
decodeFromString<TestClass>(...)
吗?

© www.soinside.com 2019 - 2024. All rights reserved.