【问题标题】:What is the recommended way of deserializing a Firestore document containing an array?反序列化包含数组的 Firestore 文档的推荐方法是什么?
【发布时间】:2017-11-10 21:14:09
【问题描述】:

我正在尝试获取包含数组的 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。如果我从模型类中删除引用字段,则对象反序列化就好了。

【问题讨论】:

    标签: android firebase kotlin google-cloud-firestore


    【解决方案1】:

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

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

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

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

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

    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 数据库中的数据:-

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

    【讨论】:

    • 对,但它不是字符串列表,而是对其他文档的 firebase DocumentReferences 数组。我会尝试使用 List 和 emptyList
    【解决方案2】:

    将我的 firebase-firestore 的 gradle 文件条目从 11.4.2 更新到 11.6.0 修复了反序列化问题。

    【讨论】:

      猜你喜欢
      • 2020-05-04
      • 2021-02-22
      • 2014-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-29
      • 2011-05-14
      • 1970-01-01
      相关资源
      最近更新 更多