RealmAnyKSerializer
KSerializer implementation for RealmAny. Serialization is done as a specific map structure that represents the a union type with all possible value types:
realmAny:
type: [INT, BOOL, STRING, BINARY, TIMESTAMP, FLOAT, DOUBLE, DECIMAL128, OBJECT_ID, UUID, OBJECT]
int: Long?
bool: Boolean?
string: String?
binary: ByteArray?
instant: RealmInstant?
float: Float?
double: Double?
decimal128: Decimal128?
objectId: ObjectId?
uuid: RealmUUID?
realmObject: RealmObject?
Content copied to clipboard
Deserialization is done with an unmanaged RealmAny.
The serializer must be registered per property:
class Example : RealmObject {
@Serializable(RealmAnyKSerializer::class)
var myInstant: RealmAny = RealmAny.create("hello world")
}
Content copied to clipboard
or per file:
@file:UseSerializers(RealmAnyKSerializer::class)
class Example : RealmObject {
var myInstant: RealmAny = RealmAny.create("hello world")
}
Content copied to clipboard
Serialization of RealmAny instances containing RealmObject require of a SerializersModule mapping such objects to the polymorphic RealmObject interface:
val json = Json {
serializersModule = SerializersModule {
polymorphic(RealmObject::class) {
subclass(SerializableSample::class)
}
}
}
Content copied to clipboard
Adding the following code snippet to a Kotlin file would conveniently register any field using a Realm datatype to its correspondent serializer:
@file:UseSerializers(
RealmListKSerializer::class,
RealmSetKSerializer::class,
RealmAnyKSerializer::class,
RealmInstantKSerializer::class,
MutableRealmIntKSerializer::class,
RealmUUIDKSerializer::class
)
Content copied to clipboard
Serializers for all Realm data types can be found in io.realm.kotlin.serializers.