Converting Kotlin objects to Maps using Jackson

Kotlin doesn’t have the ability to turn objects into maps or the other way around out of the box. However, as we’ve seen with our GSON example, converting is trivial. This time, instead of using GSON, we’ll use Jackson to convert a Kotlin object, such as a (data) class into a Map, or a Map into an object.

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 using Jackson:

import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper

val mapper = jacksonObjectMapper()

// 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 = mapper.writeValueAsString(this)
    return mapper.readValue(json, R::class.java)
}

For this code, the following Gradle dependency was used:

compile group: 'com.fasterxml.jackson.module', name: 'jackson-module-kotlin', version: '2.10.1'

Leave a Reply

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