Converting Kotlin objects to Maps using GSON

Kotlin doesn’t have the ability to turn objects into maps or the other way around out of the box. However, with a bit of help from GSON, we can turn a Kotlin object, such as a (data) class into a Map, or a Map into an object.

Note: according to Jake Wharton, GSON is deprecated and does not play well with Kotlin. Use Moshi, Jackson or kotlinx.serialization serialization instead.

Given the code below:

data class User(val name: String, val age: Int)

val map = mapOf("name" to "Peter", "age" to 20)
val user: User = map.toObject()

println(user)              // User(name=Peter, age=20)
println(user.toMap())      // {name=Peter, age=20}

We can implement the toObject and toMap extension methods as follows:

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

val gson = Gson()

// Convert a Map to an object
inline fun <reified T> Map<String, Any>.toObject(): T {
    return convert()
}

// Convert an object to a Map
fun <T> T.toMap(): Map<String, Any> {
    return convert()
}

// Convert an object of type T to type R
inline fun <T, reified R> T.convert(): R {
    val json = gson.toJson(this)
    return gson.fromJson(json, object : TypeToken<R>() {}.type)
}

For this code, the following Gradle dependency was used:

compile group: 'com.google.code.gson', name: 'gson', version: '2.8.6'

Code is based on this Stackoverflow answer.

Leave a Reply

Your email address will not be published. Required fields are marked *