我有这样的数据结构:
val drinks = hashMapOf(
"cola" to hashMapOf(
"price" to 36,
"amount" to 15
)
)
我使用Firestore并想获取价格。
db.collection("category").document("drinks").get()
.addOnSuccessListener {documentSnapshot->
documentSnapshot.data?.forEach {
//it -> Map.Entry<String!,Any!>
Log.d(TAG, "for each data: ${it.key} ${it.value}")
}
if (documentSnapshot != null && documentSnapshot.exists()) {
Log.d(TAG, "read data: ${documentSnapshot["sultan"]}")
} else {
Log.d(TAG, "Current data: null")
}
}
我试图将其转换为对象列表,但没有帮助
答案 0 :(得分:3)
使用Kotlin中的Firebase处理数据的更好方法。
.addOnSuccessListener { docsSnapshot ->
for (docSnapshot in docsSnapshot.documents) {
val hashmap = docSnapshot.data
hashmap?.put("id", docSnapshot.id)
Log.e("hashmap", hashmap) // This hashmap holds your document id and rest of data.
val Data = Gson().toJson(hashmap)
val docsData = Gson().fromJson<Drinks>(Data, Drinks::class.java)
Log.e("docsData", docsData) // Now you can access what type of data you need.
}
}
POKO为您提供数据:
class Drinks{
val id : String,
val amount : Long,
val price : Long,
}