Skip to content Skip to sidebar Skip to footer

Firebase Firestore : How To Convert Document Object To A Pojo On Android

With the Realtime Database, one could do this : MyPojo pojo = dataSnapshot.getValue(MyPojo.Class); as a way to map the object, how does one do this with Firestore? CODE : Firebas

Solution 1:

With a DocumentSnapshot you can do:

DocumentSnapshotdocument = future.get();
if (document.exists()) {
    // convert document to POJONotifPojo notifPojo = document.toObject(NotifPojo.class);
}

Solution 2:

Java

DocumentSnapshotdocument = future.get();
if (document.exists()) {
    // convert document to POJONotifPojo notifPojo = document.toObject(NotifPojo.class);
} 

Kotlin

 val document = future.get()
 if (document.exists()) {
    // convert document to POJO
     val notifPojo = document.toObject(NotifPojo::class.java)
  }

It is important to remember that you must provide a default constructor or you will get the classic deserialization error. For Java a Notif() {} should suffice. For Kotlin initialize your properties.

Solution 3:

Not sure if this is the best way to do it, but this is what I have so far.

NotifPojo notifPojo = newGson().fromJson(document.getData().toString(), NotifPojo.class);

EDIT : i'm now using what's on the accepted answer.

Post a Comment for "Firebase Firestore : How To Convert Document Object To A Pojo On Android"