【问题标题】:How to map document Reference to POJO in firestore firebase for kotlin如何在 kotlin 的 firestore firebase 中映射对 POJO 的文档引用
【发布时间】:2020-04-06 07:00:53
【问题描述】:

在此内容中是参考生物标志物/PR

data class CancerBiomarker (
    val type : String?= null,
    val biomarkers : List<Biomarkers> = emptyList()
)

data class Biomarkers(
    val title: String? = null,
    val content: Biomarker? = null
)

data class Biomarker (
    val content:String? = null
)

这是我的数据类。在该内容被声明为 Reference.After 运行后,我得到以下异常,如果我将内容更改为 DocumentReference,那么我也会得到异常

  java.lang.RuntimeException: Could not deserialize object. Can't convert object of type com.google.firebase.firestore.DocumentReference to type com.firestorepoc.model.Biomarker

如何将引用映射到 POJO 模型?

 val firebaseFirestore: FirebaseFirestore = FirebaseFirestore.getInstance()
        firebaseFirestore.collection("CancerBiomarker")
            .get()
            .addOnCompleteListener(OnCompleteListener<QuerySnapshot> { task ->
                if (task.isSuccessful) {
                    val result : MutableList<CancerBiomarker>? = task.result?.toObjects(CancerBiomarker::class.java)

                } else {
                    Log.w("Document", "Document " + "Error getting documents.", task.exception)
                }
            })

【问题讨论】:

  • 请编辑问题以显示您要映射的文档的确切数据。如果类型不匹配,您将收到该错误。该消息表明您在内容字段中存储了一个字符串,而不是一个引用。

标签: android firebase kotlin google-cloud-firestore


【解决方案1】:

您收到以下错误:

java.lang.RuntimeException:无法反序列化对象。无法将 com.google.firebase.firestore.DocumentReference 类型的对象转换为 com.firestorepoc.model.Biomarker 类型

因为您在Biomarkers 类中将content 属性声明为Biomarker 类型,而在数据库中实际上是DocumentReference。因此引发了异常,因为在 Kotlin 中无法将 DocumentReferenc 类型的对象转换为 Biomarker 类型的对象。

要解决这个问题,您必须将 content 属性更改为 DocumentReference 类型,因为它在您的数据库中。

除此之外,我看到biomarkers 属性是一个数组。如果您需要将该数组映射到 Biomarkers 对象列表 (List&lt;Biomarkers&gt;),请查看以下文章:

【讨论】:

  • 更改 val 内容时的事件:Biomarker? = null 到 val 内容:DocumentReference? = null 它抛出异常,因为无法将 java.lang.String 类型的值转换为 DocumentReference
  • 听起来你在数据库中有一些对象保存一个字符串值而不是一个 DocumentReference,对吧?
  • 在参考路径上,我有字符串值
  • 您的类中对象的类型应该与数据库中的类型相匹配。如果您在数据库中有DocumentReference,那么在您的类中,该属性应该是DocumentReference 类型。如果是字符串,则将其声明为字符串。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-20
  • 2020-07-24
  • 1970-01-01
  • 2021-09-03
  • 1970-01-01
  • 2018-03-19
  • 1970-01-01
相关资源
最近更新 更多