I've got the following data class
data class MyResponse<T>(val header: String,
val body: T)
I want to write a generic Kotlin function that can deserialise json to various MyResponse<SimpleBody>
or MyResponse<ComplexBody>
class JsonSerialiser {
val mapper = jacksonObjectMapper()
fun <T> fromJson(message: String, classz: Class<T>): T {
return mapper.readValue(message, classz)
}
}
val response: MyResponse<SimpleBody> = jsonSerialiser.fromJson("""{"header":"myheader", "body":{"simpleBody":{"name": "A"}}}""", MyResponse::class.java)
data class SimpleBody(val name: String)
It failed to compile with this error message
Kotlin: Type inference failed. Expected type mismatch: inferred type is MyResponse<*> but MyResponse<SimpleBody> was expected
Anyone knows how I can get this to work? I could use MyResponse<*> and then cast it, but I don't feel that's the right way.
Thanks & regards Tin
You don't need this, just use com.fasterxml.jackson.module.kotlin.readValue
:
val response: MyResponse<SimpleBody> = jacksonObjectMapper().readValue("""{"header":"myheader", "body":{"name": "A"}}""")
Please note that I changed the json a bit so that Jackson can parse it without further modifications