繁体   English   中英

Firebase Cloud Firestore:Kotlin Android 中自定义对象中的密封类

[英]Firebase Cloud Firestore: Sealed classes in custom objects in Kotlin Android

我正在使用

implementation 'com.google.firebase:firebase-firestore:21.3.1'

用于在版本 1.3.50 中使用 Kotlin 测试 Firestore-Database SDK。

对于读/写测试,我创建了一个简单的数据类:

data class Location(
    val uuid: String? = null,
    val name: String? = null
)

正如预期的那样,它工作正常。

但是更深入地使用 Kotlin 的密封类扩展数据类会导致序列化问题:

data class Location(
    val uuid: String? = null,
    val name: String? = null,
    val locationProperty: LocationProperty? = null
)

sealed class LocationProperty {

    data class TextProperty(
        val text: String? = null
    ) : LocationProperty()
}

虽然写入数据库工作正常,但应用程序在序列化结果时抛出异常:

document.toObject(Location::class.java)
java.lang.RuntimeException: No properties to serialize found
on class com.abc.def.LocationProperty

在 Firestore 前端,我看到我的密封类在 NoSQL 数据库中保存为Map并且接收到的DocumentSnapshot的原始数据如下所示

(locationProperty =>ArraySortedMap{(text=>My entered text)}

所以这可能会导致错误。

有没有办法解决这个问题,如果可能的话,可以通过在向 Firestore 读取或写入数据时提供自定义序列化程序?

您将无法将密封类与toObject() 那是因为密封类本身没有足够的信息来了解您实际想要读取和写入的属性。 只有继承密封类的具体类才能工作,因为反射可用于在运行时确定它们的所有属性。

Firestore 来自类反射的对象序列化根本不适合这个特定用例。 您应该提供您的数据以另存为Map<String, *> 读取文档时,数据也会以同样的方式显示。 那是因为 Firestore 在内部将您的对象与 Map 相互转换。 这将涉及编写一堆代码来使用对象的属性读取和写入该 Map 的条目,这实际上很正常。

Firestore SDK 目前没有任何“序列化器”插件的概念,可让您拦截被序列化的对象以执行转换。 您必须在编写文档之前序列化为 Map,并且在读回文档时必须从 Map 反序列化。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM