How to convert a Kotlin data class object to map?

前端 未结 6 1551
一个人的身影
一个人的身影 2020-12-09 02:39

Is there any easy way or any standard library method to convert a Kotlin data class object to a map/dictionary of it\'s properties by property names? Can reflection be avoid

6条回答
  •  长情又很酷
    2020-12-09 03:24

    I was using the jackson method, but turns out the performance of this is terrible on Android for first serialization (github issue here). And its dramatically worse for older android versions, (see benchmarks here)

    But you can do this much faster with Gson. Conversion in both directions shown here:

    import com.google.gson.Gson
    import com.google.gson.reflect.TypeToken
    
    val gson = Gson()
    
    //convert a data class to a map
    fun  T.serializeToMap(): Map {
        return convert()
    }
    
    //convert a map to a data class
    inline fun  Map.toDataClass(): T {
        return convert()
    }
    
    //convert an object of type I to type O
    inline fun  I.convert(): O {
        val json = gson.toJson(this)
        return gson.fromJson(json, object : TypeToken() {}.type)
    }
    
    //example usage
    data class Person(val name: String, val age: Int)
    
    fun main() {
    
        val person = Person("Tom Hanley", 99)
    
        val map = mapOf(
            "name" to "Tom Hanley", 
            "age" to 99
        )
    
        val personAsMap: Map = person.serializeToMap()
    
        val mapAsPerson: Person = map.toDataClass()
    }
    

提交回复
热议问题