Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/227.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Firebase Firestore:如何在Android上将文档对象转换为POJO_Java_Android_Firebase_Google Cloud Firestore - Fatal编程技术网

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

Java Firebase Firestore:如何在Android上将文档对象转换为POJO,java,android,firebase,google-cloud-firestore,Java,Android,Firebase,Google Cloud Firestore,使用实时数据库,您可以执行以下操作: MyPojo pojo = dataSnapshot.getValue(MyPojo.Class); 作为映射对象的一种方式,如何使用Firestore 代码: FirebaseFirestore db = FirebaseFirestore.getInstance(); db.collection("app/users/" + uid).document("notifications").get().addOnCompleteListe

使用实时数据库,您可以执行以下操作:

MyPojo pojo  = dataSnapshot.getValue(MyPojo.Class);
作为映射对象的一种方式,如何使用
Firestore

代码:

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

不确定这是否是最好的方法,但这就是我目前所拥有的

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

编辑:我现在正在使用已接受答案上的内容

使用
文档快照
可以执行以下操作:

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

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

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

请务必记住,必须提供默认构造函数,否则将出现经典的反序列化错误。对于Javaa
Notif(){}
就足够了。对于Kotlin初始化属性

这会携带文档id吗?知道这使用的是什么类型的反序列化程序吗?如果可能的话,我想在pojo中为反序列化程序配置一些指令。有点像杰克逊提供的。我正在尝试反序列化到一个枚举。我找到了一个保持文档id的答案:初始化数据类的属性是我的关键。我有一个未初始化的参数。谢谢你指出这一点。