natario1
09/10/2020, 11:10 AMclass 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:
@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.ephemient
09/10/2020, 7:09 PMnatario1
09/10/2020, 7:25 PMuser["_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?ephemient
09/10/2020, 7:25 PMephemient
09/10/2020, 7:25 PMephemient
09/10/2020, 7:26 PMnatario1
09/10/2020, 7:29 PMephemient
09/10/2020, 8:07 PM