最好的方法是,应该使用与保存数据相同的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);
}
}
});
,
- 首先,您的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