2

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

Tin Ng
  • 937
  • 2
  • 11
  • 25

1 Answers1

0

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

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
  • I have a generic message listener than can accept any kind of payload, and I want to be able to parse the payload to a generic type and then call appropriate handler s based on the topic mapping. So I don't know if it's `SimpleBody` or not. Can I still achieve that somehow? `override fun messageArrived(topic: String?, message: MqttMessage?) { mapper.readValue>(String(message.payload))}` – Tin Ng Aug 21 '18 at 21:40
  • 1
    readvalue takes 2 parameters this answer makes no sense – Rafael Lima Jun 15 '22 at 23:53