简体   繁体   English

Firebase Firestore:如何在Android上将文档对象转换为POJO

[英]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 ? 作为映射对象的一种方式,如何使用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());
            }
        });

With a DocumentSnapshot you can do: 使用DocumentSnapshot您可以:

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

Java 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. 对于JavaNotif() {}应该足够了。 For Kotlin initialize your properties. 对于Kotlin,初始化您的属性。

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. 编辑:我现在正在使用接受的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM