Jackson Kotlin extension and reified types

Biju Kunjummen
2 min readMay 30, 2023

Jackson Kotlin module library greatly simplifies gnarly code involving TypeReference.

Consider a sample json which looks like this:

{
"a" : ["b", "c"],
"b" : ["a", "c"],
"c" : ["a", "b"]
}

This content can be represented as a `Map<List<String>>` type in Java.

So now, if I were to use straight Java to convert the string to the appropriate type, the code would look like this:

Map<String, List<String>> result = 
objectMapper.readValue(json, new TypeReference<>() { });

What exactly is “TypeReference” doing there… think of it as a way of making the type parameters of the generic type “Map” which are “String” and “List”, available at runtime. Without it, the types are erased at runtime and Java would not know that it has to create a “Map<String, List<String>>”. More details here

Kotlin can hide this detail behind an extension function which if defined from scratch would look like this:

inline fun <reified T> ObjectMapper.readValue(src: String): T = readValue(src, object : TypeReference<T>() {})

and a code using such an extension function:

val result: Map<String, List<String>> = objectMapper.readValue(json)

See how all the TypeReference code is hidden in the extension function.

This is the kind of capability that is provided by the Jackson Kotlin Module

With the suitable packages imported, a sample code with this module looks like this:

import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper 
import com.fasterxml.jackson.module.kotlin.readValue
val objectMapper = jacksonObjectMapper()
val result: Map<String, List<String>> = objectMapper.readValue(json)

This is just one of the simplifications offered by using the module.

It also supports features like Kotlin Data classes, Kotlin built-in types like Pair, Triple, etc. out of the box.

Highly recommended if you are using Jackson with Kotlin.

Originally published at http://www.java-allandsundry.com.

--

--

Biju Kunjummen

Sharing knowledge about Java, Cloud and general software engineering practices