【问题标题】:Serializing Lists with external kotlinx Serializer使用外部 kotlinx 序列化器序列化列表
【发布时间】:2019-06-17 15:39:44
【问题描述】:

所以,我有这个类 Item.kt

class Item {
    val name = ""
    val loc = ""
    val price = 0.0
    override fun toString() = "$name <$loc> $price"
}

由于这个类在另一个库中(我无法编辑它的源代码),所以我有一个外部序列化器。

ItemSerializer.kt

@Serializer(forClass = Item::class)
object ItemSerializer: KSerializer<Item> {
    override fun serialize(output: Encoder, obj: Item) {

    }

    override fun deserialize(input: Decoder): Item {
        return df.parse(input.decode())
    }
}

现在,困难的部分来了。我可以在下面显示的另一个类中使用这个类

购物车.kt

@Serializable
class Cart {
    val id: Long? = null
    @Serialize(with=ItemSerializer::class)
    val item:Item = Item()
}

但是当我使用项目对象列表时,我不知道如何使用我的序列化程序。例如

购物车.kt

@Serializable
class Cart {
    val id: Long? = null
    @Serialize(with=ItemSerializer::class) // doesn't work
    val items = mutableListOf<Item>()
}

我应该如何使用 kotlinx 序列化?我是否必须编写一个全新的库来序列化 Item 实现的列表和映射?

【问题讨论】:

    标签: kotlin kotlinx.serialization


    【解决方案1】:

    现在,只需在文件的最开头(在您的包名称之前)添加这样的文件注释语句

    @file:useSerializer(ItemSerializer::class)
    package blah.blah
    

    【讨论】:

    • 正确的语法是:@file:UseSerializers(ItemSerializer::class)
    猜你喜欢
    • 2019-12-31
    • 2020-12-05
    • 2021-02-24
    • 2020-11-20
    • 2021-05-14
    • 1970-01-01
    • 2020-02-15
    • 2020-01-23
    • 2021-03-25
    相关资源
    最近更新 更多