在Kotlin中将地图转换为对象

时间:2018-05-03 17:18:30

标签: java json firebase object kotlin

大家好我有一个简单的问题, 我有一个充满元素的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
    }
}

还有我要转换的地图:

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)
        }
    }
}

谢谢!

1 个答案:

答案 0 :(得分:4)

好的,我找到了解决方案

我在数据类中转换了我的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)