如何将Google Cloud Firestore的documentSnapshot.getData()返回的Map <String,Object>的对象解析为POJO?

Cloud Firestore的

documentsnapshot.getData()方法返回Map 。我的数据库结构如下所示:

如何将Google Cloud Firestore的documentSnapshot.getData()返回的Map <String,Object>的对象解析为POJO?

现在我有一个POJO,如下所示:

$i=1;
$result = array();

foreach ($boxes as $key => $value) {
    $result[] = $i."/".count($value);//assign value to array
    foreach ($result as $k => $val) {
        if(in_array($i."/".count($value),$result)){//check value is in array or not
            echo "-".'</br>'; //if yes then add -
        }else{
            echo $i."/".count($value).'</br>'; // if not then show the value
        }
    }
    $i++;
}

如您所见,我所需要的只是从documentsnapshot.getData()方法返回的Map 中的Object列表。字符串,即关键部分,必须忽略。我不想使用键从Map中提取数据,因为我希望算法能够动态创建所有计划的列表(POJO),而不管映射中键/值对的数量如何。

以下是我正在使用的代码:

google_sign_in: 4.0.6

我尝试了很多方法,但是无法将该对象解析为POJO。请帮忙。预先感谢。

a258543020 回答:如何将Google Cloud Firestore的documentSnapshot.getData()返回的Map <String,Object>的对象解析为POJO?

最好的方法是,应该使用与保存数据相同的POJO类。由于它是一个复杂的类,并且具有Plan类的对象,因此,如果使用该类会更好。让您的原始班级名称为Familiy_pack。

documentReference.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
            @Override
            public void onSuccess(DocumentSnapshot documentSnapshot) {
                if (documentSnapshot.exists()) {
                   Family_pack f = documentSnapshots.toObject(Family_pack .class);


                    }
                }
            }
        });

现在,使用可以轻松地从Plan对象获取值。

,

更新:如果需要对象列表,请参考Convert DocumentSnapshot Data to List

官方文件说

 <T> T toObject(Class<T> valueType) - 
 Returns the contents of the document converted to a POJO or null if the document doesn't exist.

所以尝试

Plan plan = documentSnapshots.toObject(Plan.class);

Ref-https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/DocumentSnapshot

,

尝试用QuerySnapshot代替DocumentSnapshot

documentReference.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
            @Override
            public void onSuccess(QuerySnapshot documentSnapshot) {
                if (documentSnapshots.isEmpty()) {
                    Log.d(TAG,"onSuccess: LIST EMPTY");
                    return;
                } else {
                    // Convert the whole Query Snapshot to a list
                    // of objects directly! No need to fetch each
                    // document.
                    List<Plan> plans = documentSnapshot.toObjects(Plan.class);   

                    // Add all to your list
                    mArrayList.addAll(types);
                    Log.d(TAG,"onSuccess: " + mArrayList);
                }
            }
        });
,
  1. 首先,您的POJO允许通过您的实例访问您的实例变量             构造函数。我认为您将它们设为私有是有充分理由的。             考虑删除构造函数。

使用GSON,您可以尝试以下操作。

Gson gson = new Gson(); 
JsonElement jsonElement = gson.toJsonTree(documentSnapshot.getData());
MyPojo pojo = gson.fromJson(jsonElement,MyPojo.class);
本文链接:https://www.f2er.com/2862840.html

大家都在问