w

    Waqas Tahir

    1 year ago
    Hi Everyone ! Let's say I have a class that extends List class , and I am using it as a property in another class that I want to serialize , How can I write serializer , I just want to cast that property to a List and then serialize and deserialize as a List , does anyone reply here ?
    w

    Waqas Tahir

    1 year ago
    class SnapshotListSerializer<T>(private val dataSerializer: KSerializer<T>) :
        KSerializer<SnapshotStateList<T>> {
    
        override val descriptor: SerialDescriptor = ListSerializer(dataSerializer).descriptor
    
        override fun serialize(encoder: Encoder, value: SnapshotStateList<T>) {
            val list = value as List<T>
            encoder.encodeSerializableValue(ListSerializer(dataSerializer), list)
        }
    
        override fun deserialize(decoder: Decoder): SnapshotStateList<T> {
            val list = mutableStateListOf<T>()
            val items = decoder.decodeSerializableValue(ListSerializer(dataSerializer))
            list.addAll(items)
            return list
        }
    }
    I've written this serializer , that I can specify , do you think it should work ?
    b

    Ben Woodworth

    1 year ago
    Yeah that looks good to me! In
    serialize
    you probably don't even need to make a separate List variable, just pass value directly
    w

    Waqas Tahir

    1 year ago
    error: incompatible types: Class<SnapshotListSerializer> cannot be converted to Class<? extends KSerializer<?>> @kotlinx.serialization.Serializable(utils.serializers.SnapshotListSerializer.class)
    Used it like this
    @Serializable(with = SnapshotListSerializer::class)
    val items = mutableStateListOf<ListItem>()
    b

    Ben Woodworth

    1 year ago
    Does mutableStateListOf() return a subtype of SnapshotStateList? Because you'll have to write a serializer specifically for MutableStateList. (Your serializer only creates a SnapshotStateList, so kotlinx.serialization doesn't know how to turn it into a mutable one)
    w

    Waqas Tahir

    1 year ago
    mutableStateListOf returns SnapshotStateList , I am getting this everywhere where I specified a serializer as a parameter in the annotation , think some kind of bug or something , let me know if you know about it , Thanks for the help though !!
    b

    Ben Woodworth

    1 year ago
    If SnapshotStateList is an interface then that might be the problem (@Serializable doesn't work on interfaces). But that's the only thing I can think of... glad I could help!