如何解决将Firestore文档转换为对象图
我的Firestore文档具有以下格式的数据
{
m1: {
name: "first"
},m2: {
name: "second"
},m3: {
name: "third"
},...
}
字段名称事先未知。但是每个字段都是地图类型,包含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)
解决方法
类似这样的事情应该可以解决:
imageSubject.onNext(imageSubject.value ?: someDefaultValue)
您将不得不遍历结果并将其转换为document?.data?.forEach { item ->
val fieldName = item.key
val fieldValue = item.value
}
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。