Firebase Firestore : How to convert document object to a POJO on Android
21,947
Solution 1
With a DocumentSnapshot
you can do:
DocumentSnapshot document = future.get();
if (document.exists()) {
// convert document to POJO
NotifPojo notifPojo = document.toObject(NotifPojo.class);
}
Solution 2
Java
DocumentSnapshot document = future.get();
if (document.exists()) {
// convert document to POJO
NotifPojo 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 = new Gson().fromJson(document.getData().toString(), NotifPojo.class);
EDIT : i'm now using what's on the accepted answer.
![Relm](https://i.stack.imgur.com/IBvqk.jpg?s=256&g=1)
Author by
Relm
Updated on September 20, 2020Comments
-
Relm almost 4 years
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 :
FirebaseFirestore db = FirebaseFirestore.getInstance(); db.collection("app/users/" + uid).document("notifications").get().addOnCompleteListener(task -> { if (task.isSuccessful()) { DocumentSnapshot document = task.getResult(); if (document != null) { NotifPojo notifPojo = document....// here return; } } else { Log.d("FragNotif", "get failed with ", task.getException()); } });
-
Alexander N. over 6 yearsWill this carryover the document id?
-
Hilikus over 6 yearsany idea what kind of deserializer this is using? i would like to configure some directives in my pojo for the deserializer if possible. Kind of like what Jackson provides. I'm trying to deserialize to an enum
-
Johnny over 6 yearsI found an answer to keep document id : stackoverflow.com/a/46999773/2529315
-
Mikkel Jørgensen over 5 yearsInitializing the properties for my data class was the key for me. I had a parameter that was not initialised. Thank you for pointing this out.