【发布时间】:2026-02-10 10:45:01
【问题描述】:
我的 Firestore 文档包含以下格式的数据
{
m1: {
name: "first"
},
m2: {
name: "second"
},
m3: {
name: "third"
},
...
}
字段名称事先不知道。但是每个字段都是map类型,包含name字段。
我正在尝试将此文档转换为<String, Listing> 类型的地图,其中Listing 是带有name 的数据类。
data class Listing(
val name: String = ""
)
data class ListingDoc(
val listingMap: Map<String, Listing>? = null
)
我尝试了以下code to convert the document 没有成功。 document.toObject() 在对象字段事先已知并存在于数据类中时起作用。
db.collection("Listings")
.document("trial").get()
.addOnSuccessListener { document ->
if (document != null) {
try {
Timber.d("Got document ${document.data}")
val listingDocument = document.toObject(ListingDoc::class.java)
Timber.d("Got listings: $listingDocument")
} catch (exception: Exception) {
Timber.d("Error converting listings: ${exception.message}")
}
}
}
这是 logcat 输出
2020-08-14 15:27:16.317 19258-19258/com.myapp D/StoreViewModel$getListings: Got document {m1={name=first}, m2={name=second}}
2020-08-14 15:27:16.324 19258-19258/com.myapp W/Firestore: (21.5.0) [CustomClassMapper]: No setter/field for m1 found on class com.myapp.store.ListingDoc
2020-08-14 15:27:16.327 19258-19258/com.myapp W/Firestore: (21.5.0) [CustomClassMapper]: No setter/field for m2 found on class com.myapp.store.ListingDoc
2020-08-14 15:27:16.328 19258-19258/com.myapp D/StoreViewModel$getListings: Converted listings: ListingDoc(listingMap=null)
【问题讨论】:
标签: android firebase kotlin generics google-cloud-firestore