有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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

共 (3) 个答案

  1. # 1 楼答案

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

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

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

  2. # 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)
      }
    

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

  3. # 3 楼答案

    使用DocumentSnapshot可以执行以下操作:

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