You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Firestore文档的Map字段转为Kotlin的List<Schedule>对象

解决Firestore文档转Kotlin List的问题

问题原因

你的Firestore文档结构是顶级字段为多个Map类型的Schedule数据(比如截图中的08:00、09:00等字段),但你定义的DailySchedules类期望文档中有一个名为list的数组字段,两者结构不匹配,所以toObject后list始终为null。

修正步骤

1. 修复数据类的错误

你的Schedule类中attendees字段引用了不存在的userList,需要改为users:

data class Schedule (
    val opo: String? = null,
    val startTime: Long? = null,
    val duration: Int? = null,
    val maxCapacity: Int? = null,
    val users: Map<String,String>? = null,
    val coachName: String? = null,
    val coachImage: String? = null
) {
    // 修正为users字段
    val attendees: Int = users?.size ?: 0
}

2. 修改仓库层转换逻辑

不需要DailySchedules类,直接遍历文档的所有顶级字段,将每个字段的Map数据转换为Schedule对象,再收集为List:

override fun getDailySchedules(date: String) = callbackFlow {
    val schedulesDoc = schedulesRef.document(date)

    val snapshotListener = schedulesDoc.addSnapshotListener { snapshot, e ->
        val dbResponse = if (snapshot != null && snapshot.exists()) {
            // 获取文档所有字段的键值对
            val scheduleEntries = snapshot.data?.entries ?: emptyList()
            // 遍历转换为Schedule列表
            val schedules = scheduleEntries.mapNotNull { entry ->
                // 将每个字段的Map值转换为Schedule对象
                entry.value?.let { value ->
                    if (value is Map<*, *>) {
                        Firebase.firestore.convertValue(value).toObject<Schedule>()
                    } else {
                        null
                    }
                }
            }
            Log.d("PROVES", schedules.toString())
            Success(schedules)
        } else {
            Failure(e ?: Exception("文档不存在或读取失败"))
        }
        trySend(dbResponse)
    }
    awaitClose { snapshotListener.remove() }
}

关键说明

  • Firestore的toObject(Class<T>)是针对整个文档结构匹配类的字段,你的文档没有list字段,所以DailySchedules无法匹配。
  • 遍历文档的data?.entries可以拿到所有顶级字段的键值对,每个值就是单个Schedule对应的Map结构,逐个转换即可得到List。

内容的提问来源于stack exchange,提问作者Alex Diaz Llagostera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 12:52:52