Search code examples
kotlinkotlinx.serialization

Serializing Lists with external kotlinx Serializer


So, I have this class Item.kt

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

Since this class is in another library (I can't edit its source), I have an external Serializer for it.

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())
    }
}

Now, comes the hard part. I can use this class in another class a shown below

Cart.kt

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

but I dont know how to make a utilize my serializer when ever I use a list of item objects. e.g.

Cart.kt

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

How should I go about it using kotlinx serialization? do I have to write a whole new lib for serializing a list and a map of the Item implementation?


Solution

  • for now, just add a file annotation statement like this at the very beginning of your file (before your package name)

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