Convert a Map to an Object in Kotlin

10,382

Ok I found the solution

I transformed my Bundle class in a data class :

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
)

And then I simply added this on my method , where I want to convert my Map to my Bundle Object :

val myObject = document.toObject(Bundle::class.java)
Share:
10,382

Related videos on Youtube

Manu13k
Author by

Manu13k

Updated on June 04, 2022

Comments

  • Manu13k
    Manu13k almost 2 years

    Hello guys I have a simple question , I have a Map full of element and I want to convert It in my Object , let me show you some code :

    Here is my 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
        }
    }
    

    And there is the Map that i want to convert:

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

    Thank you !

    • hotkey
      hotkey almost 6 years
      What is exactly the problem that you are trying to solve?
    • ice1000
      ice1000 almost 6 years
      Can't be uglier.. Why ArrayList<Any>? with = arrayListOf()? Why so many Anys?
    • Manu13k
      Manu13k almost 6 years
      @hotkey The problem that i'm trying to solve is , how can I convert my map in my Bundle object
    • Manu13k
      Manu13k almost 6 years
      @ice1000 sorry about this I'm new in Kotlin , I thought it was the good way to initialize
    • jrtapsell
      jrtapsell almost 6 years
      Generally, you want to avoid Any and ? as much as you can, the more specific you can be about a type, the less likely it is to not be what you expect when you go to use it.