Reputation:
I want to convert a mutable map to Any object. For example:
Val map = mutableMapOf("name" to "michael", "age" to "12")
Var user = map.toObject //Any Object i want
And :
Print((user as User).name)
//output michael
Print((user as User).age)
//output 12
Class User(val name, val age){
}
because I am creating a generic function. by what way do this?
Upvotes: 0
Views: 5118
Reputation: 1322
You can do this with Gson, by serializing the map to json, and then deserializing the json to any object. Conversion in both directions shown here:
val gson = Gson()
//convert a map to a data class
inline fun <reified T> Map<String, Any>.toDataClass(): T {
return convert()
}
//convert a data class to a map
fun <T> T.serializeToMap(): Map<String, Any> {
return convert()
}
//convert an object of type I to type O
inline fun <I, reified O> I.convert(): O {
val json = gson.toJson(this)
return gson.fromJson(json, object : TypeToken<O>() {}.type)
}
See similar question here
Upvotes: 3