gpt4 book ai didi

java - 在 Kotlin 中将映射转换为对象

转载 作者:行者123 更新时间:2023-12-01 17:50:59 24 4
gpt4 key购买 nike

大家好,我有一个简单的问题,我有一个充满元素的 Map,我想将其转换为我的 Object ,让我向您展示一些代码:

这是我的对象:

class Bundle(map: Map<String, Any>) {
var version: String?
var app: String?
var countries: ArrayList<Any>?
var currency: ArrayList<Any>?
var force: Boolean?
var name: String?
var service: ArrayList<Any>?
var money: Int?

init {
version= null
app= null
countries= arrayListOf()
currency= arrayListOf<Any>()
force= true
name = ""
service= arrayListOf<Any>()
money= 0
}
}

还有我想要转换的 map :

fun getBundle() {

var db = FirebaseFirestore.getInstance()
val docRef = db.collection("aa").document("bb")

docRef.get().addOnCompleteListener { task ->
if (task.isSuccessful) {
val document = task.result
if (document.exists()) {
Log.d("Doc", "DocumentSnapshot data: " + document.data!!)
// Here i want to take (document.data!!) and convert it to my Bundle class

} else {
Log.d("NO doc", "No such document")
}
} else {
Log.d("ERROR", "get failed with ", task.exception)
}
}
}

谢谢!

最佳答案

好的,我找到了解决方案

我将 Bundle 类转换为数据类:

data class Bundle(
var version: String? = null,
var app: String? = null,
var countries: ArrayList<Any> = arrayListOf(),
var currency: HashMap<String, Any> = hashMapOf(),
var force: Boolean = false,
var name: String? = null,
var service: ArrayList<Any> = arrayListOf(),
var money: Int = 0
)

然后我只是将其添加到我的方法中,我想将我的 Map 转换为我的 Bundle 对象:

val myObject = document.toObject(Bundle::class.java)

关于java - 在 Kotlin 中将映射转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50160654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com