gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 09:31:09 24 4
gpt4 key购买 nike

我正在尝试获取包含数组的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com