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

What is the recommended way of deserializing a Firestore document containing an array?

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

下面是我的模型class

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

}

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

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

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

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

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

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

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