Hi :wave: I have many model classes extending a ba...
# serialization
n
Hi 👋 I have many model classes extending a base interface like:
Copy code
class BaseModel {
    val keys: Set<String> 
    fun <T> get(key: String): T?
    fun <T> set(key: String, value: T?)
}
Basically, it works as a
Map<String, Any?>
and we can assume that the actual values are something that can be serialized, like numbers or strings. Then I have concrete models e.g.
class UserModel : BaseModel
,
class PostModel : BaseModel
and so on. How can I make these classes serializable? I tried to write a common KSerializer and can handle serialization like:
Copy code
@Serializer(UserModel::class)
object UserSerializer : BaseSerializer<UserModel>({ UserModel() })

@Serializer(PostModel::class)
object PostSerializer : BaseSerializer<PostModel>({ PostModel() })

class BaseSerializer<M : BaseModel>: KSerializer<M> {

    override fun serialize(encoder: Encoder, model: T) {
        for (key in model.keys) {
            encoder.encodeString(key)
            val value = model.get(key)
            when (value) {
                is Int -> encoder.encodeInt(value)
                is Long -> encoder.encodeLong(value)
                is String -> encoder.encodeString(value)
                else -> error()
            }
        }
    }
}
But then I have no idea of how to implement
deserialize
(looks like order matters there...?) and
descriptor: SerialDescriptor
(not even sure what this is). I might get it working but I don't think I'm doing things in the correct way. Can anyone help? The BaseModel also has a working Parcelable implementation, if that matters.
e
something like this?
n
This is very helpful @ephemient, thanks! Learned a lot by going through your code. But what if I don't know the model fields? For example, User can have name and age, but occasionally I can also call
user["_extraRuntimeProperty"] = foo
and I want these properties to be serialized as well. Basically I don't know the model schema at compile time... How should I write the descriptor in this case?
e
you can't
😄
in that case you may want to just treat the whole thing as a Map
n
In fact it really is a map (a bit more complex because these models can be nested, but we can ignore it for now). But I'm still not sure about how to implement serialization for it 😅
assuming you're not too picky about the exact format