【问题标题】:Firebase Firestore : How to convert document object to a POJO on AndroidFirebase Firestore:如何在 Android 上将文档对象转换为 POJO
【发布时间】:2018-03-20 05:55:12
【问题描述】:

使用实时数据库,可以做到这一点:

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

【问题讨论】:

    标签: java android firebase google-cloud-firestore


    【解决方案1】:

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

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

    【讨论】:

    • 初始化我的数据类的属性是我的关键。我有一个未初始化的参数。感谢您指出这一点。
    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

      使用DocumentSnapshot,您可以:

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

      【讨论】:

      • 这会带走文档ID吗?
      • 知道这使用的是哪种反序列化器吗?如果可能的话,我想在我的 pojo 中为反序列化器配置一些指令。有点像杰克逊提供的。我正在尝试反序列化为枚举
      • 我找到了保留文档 ID 的答案:stackoverflow.com/a/46999773/2529315
      猜你喜欢
      • 2019-01-24
      • 2020-12-04
      • 1970-01-01
      • 2017-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-13
      相关资源
      最近更新 更多