Ragini
Ragini

Reputation: 775

How to map document Reference to POJO in firestore firebase for kotlin

enter image description here In this content is Reference to Biomarkers/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
)

This is my data class. In that content is declared as Reference.After running this I am getting following exception and if I change content to DocumentReference then also I am getting exception

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

How to map reference to POJO model?

 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)
                }
            })

Upvotes: 0

Views: 2075

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138999

You are getting the following error:

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

Because you have declared the content property in your Biomarkers class to be of type Biomarker, while in the database is actually a DocumentReference. So the exception is raised because there is no way in Kotlin in which you can cast an object of type DocumentReferenc to an object of type Biomarker.

To solve this, you have to change the content property to be of type DocumentReference as it is in your database.

Besides that, I see that the biomarkers property is an array. If you need to map that array to a list of Biomarkers objects (List<Biomarkers>), please check out the following article:

Upvotes: 1

Related Questions