【问题标题】:Convert Firestore document to map of objects将 Firestore 文档转换为对象图
【发布时间】: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


    【解决方案1】:

    这样的事情应该可以解决问题:

    document?.data?.forEach { item ->
        val fieldName = item.key
        val fieldValue = item.value
    }
    

    您必须遍历结果并将其转换为 ListingDoc

    【讨论】:

    • 使用document.get("trial") 给出一个空值。这里trial 是文档名称,而不是字段。我用document.getData() 尝试了你的代码,但它给出了错误java.util.HashMap cannot be cast to java.util.List
    • 这段代码产生错误:java.util.HashMap cannot be cast to