VOOZH about

URL: https://www.javacodegeeks.com/2021/03/jackson-kotlin-extension-and-reified-types.html

⇱ Jackson Kotlin extension and reified types - Java Code Geeks


Jackson Kotlin module library is a pleasure to use. It greatly simplifies gnarly code, specifically one’s involving
TypeReference

Consider a sample json which looks like this:

1
2
3
4
5
{
    "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:

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

What exactly is that “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 that the types are erased at runtime and Java would not know that it has to create a “Map<String, List<String>>”.

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

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

and a code using such an extension function:

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

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

This is the kind of capability that is provided by the
Jackson Kotlin Module With the right packages imported a sample code with this module looks like this:

1
2
3
4
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 the use of 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.

Published on Java Code Geeks with permission by Biju Kunjummen, partner at our JCG program. See the original article here: Jackson Kotlin extension and reified types

Opinions expressed by Java Code Geeks contributors are their own.

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

👁 Photo of Biju Kunjummen
Biju Kunjummen
March 12th, 2021Last Updated: March 11th, 2021
0 512 1 minute read
Back to top button
Close
wpDiscuz