将Firestore文档转换为对象图

时间:2020-08-14 10:08:04

标签: android firebase kotlin generics google-cloud-firestore

我的Firestore文档具有以下格式的数据

{
    m1: {
        name: "first"
    },
    m2: {
        name: "second"
    },
    m3: {
        name: "third"
    },
    ...
}

Firestore document

字段名称事先未知。但是每个字段都是地图类型,包含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)

1 个答案:

答案 0 :(得分:2)

类似这样的事情应该可以解决:

imageSubject.onNext(imageSubject.value ?: someDefaultValue)

您将不得不遍历结果并将其转换为document?.data?.forEach { item -> val fieldName = item.key val fieldValue = item.value }