android - 反序列化包含数组的 Firestore 文档的推荐方法是什么?

标签 android firebase kotlin google-cloud-firestore

我正在尝试获取包含数组的 Firestore 文档,但是,我无法在添加数组后立即使 DocumentSnapshot.toObject 方法正常工作。我不想使用集合,因为数组可能最多只包含 1-2 个项目。

java.lang.RuntimeException: Could not deserialize object. Failed to convert value of type com.google.android.gms.internal.zzegf to DocumentReference (found in field 'references.[0]')

下面是我的模型类

data class SomeModel(
        var references : ArrayList<DocumentReference> = ArrayList(0),
        var title : String? = null,
        var acronym : String? = null,
        var number : Long? = null
){

}

我的 Firestore 文档包含一个名为 references 的数组和一个 DocumentReference。如果我从模型类中删除引用字段,对象反序列化就好了。

最佳答案

如果我想检索单个文档中的项目列表,我可以这样做:-

包含字符串列表的数据类,列表可以是任何类型

注意:- 我为所有参数提供默认值,为了反序列化,类必须有空承包商。

 data class SomeModel(val references : List<String> = emptyList() , val title : String = "" , val acronym  : String = "" , val number : Long = 0L)

然后我可以指向这个单个文档并以这种方式反序列化它,包括文档中的 itmes 列表:-

val db = FirebaseFirestore.getInstance()
    val someModelRef = db.collection("someCollection").document("SomeModel")
    someModelRef.get().addOnSuccessListener {
        val someModel : SomeModel = it.toObject(SomeModel::class.java)

        someModel.references.forEach {
            Log.i("MainActivity","items $it")
        }

    }

firestore 数据库中的数据:-

enter image description here

当我运行上面的代码时我的 logcat 中的输出

enter image description here

关于android - 反序列化包含数组的 Firestore 文档的推荐方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47231221/

相关文章:

android.util.AndroidRuntimeException : You cannot combine swipe dismissal and the action bar

android - com.android.dx.util.DexException : Multiple dex files define

java - 动画在特定时间开始

Android PDF页面转图片api

javascript - 如何让 Firestore 交易返回 promise ?

javascript - 链接多个 firebase 操作和回滚

ios - 如何通过swift3在firebase中24小时内删除数据

list - Kotlin:以功能性方式组合列表中的某些元素

android - Koin 2 在 Android 项目中创建功能范围的问题

java - Spring 5 和 Kotlin 1.1 协程 : Type rx. 调度程序不存在