代码之家  ›  专栏  ›  技术社区  ›  andylamax

使用外部Kotlinx序列化程序序列化列表

  •  0
  • andylamax  · 技术社区  · 6 年前

    所以,我有这个班级的项目.kt

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

    因为这个类在另一个库中(我不能编辑它的源代码),所以我有一个外部序列化程序。

    项序列化程序.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())
        }
    }
    

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

    凯特汽车

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

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

    凯特汽车

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

    我应该如何使用Kotlinx序列化来实现它?我是否需要编写一个全新的lib来序列化列表和映射 Item 实施?

    1 回复  |  直到 6 年前
        1
  •  0
  •   andylamax    6 年前

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

    @file:useSerializer(ItemSerializer::class)
    package blah.blah
    
    推荐文章