Jackson convertValue() does not work with reified type parameters in Kotlin

454 Views Asked by At

I expected this to return a list of Money objects, but it returns LinkedHashMap instead, which is the generic fallback type I guess. It seems the reified type parameter is not being propagated, even though it should.

Here is a self-contained example (dependencies: assertj, junit, jackson-databind, kotlin-1.4.32):

import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module
import com.fasterxml.jackson.module.kotlin.KotlinModule
import com.fasterxml.jackson.module.kotlin.convertValue
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test

class MapperTest {

    val JSON_MAPPER = ObjectMapper().apply {
        registerModule(KotlinModule())
        registerModule(Jdk8Module())
    }

    data class Money(@JsonProperty("Currency") val currency: String?)

    @Test
    fun testMapper() {
        val map = listOf(mapOf("Currency" to "EUR"))

        assertThat(fromMap(map)[0]).isInstanceOf(Money::class.java) // passes
        assertThat(fromMapReified<Money>(map)[0]).isInstanceOf(Money::class.java) // fails
    }

    private fun fromMap(map: List<Map<String, String>>) : List<Money> {
        return JSON_MAPPER.convertValue(map)
    }

    private inline fun <reified T> fromMapReified(map: List<Map<String, String>>) : List<T> {
        return JSON_MAPPER.convertValue(map)
    }

}
0

There are 0 best solutions below