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

Rel*_*elm 14 java android firebase google-cloud-firestore

使用实时数据库,可以这样做:

MyPojo pojo  = dataSnapshot.getValue(MyPojo.Class);
Run Code Online (Sandbox Code Playgroud)

作为一种映射对象的方法,人们如何做到这一点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());
            }
        });
Run Code Online (Sandbox Code Playgroud)

Gab*_*tti 22

有了DocumentSnapshot你可以这样做:

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

  • 这会遗留文件ID吗? (4认同)
  • 知道这是使用什么样的解串器吗?如果可能的话,我想在我的 pojo 中为解串器配置一些指令。有点像杰克逊提供的。我正在尝试反序列化为枚举 (4认同)

Joe*_*oel 5

爪哇

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

科特林

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

重要的是要记住,您必须提供一个默认构造函数,否则会出现经典的反序列化错误。对于Java, aNotif() {}就足够了。对于Kotlin,初始化您的属性。