8

I'm posting json array of objects. I'm trying to parse it in code like this

val objs = call.receive<List<MyClass>>() // this work fine
val name objs[0].name // this throw exception LinkedTreeMap cannot be cast to MyClass

In above code second line throws exception com.google.gson.internal.LinkedTreeMap cannot be cast to MyClass

If i post simple object and parse it in ktor with call.receive<MyClass>() then it will work fine. So issue is only when parsing list of objects.

William
  • 225
  • 4
  • 21

2 Answers2

5

Using your code with Array instead of List worked for me using ktor v1.2.3:

val objs = call.receive<Array<MyClass>>() 
val name = objs[0].name


Side Note:

I later changed my data class to this format to help with mapping from database rows to a data class (i.e. to use BeanPropertyRowMapper). I don't remember this having an effect on de/serialization, but if the first part still isn't working for you, you may try this...

data class MyClass(
    var id: Int? = null,
    var name: String? = null,
    var description: String? = null,
)

Reference: Kotlin data class optional variable

cs_pupil
  • 2,782
  • 27
  • 39
3

You can do like this

val json = call.receive<String>()
val objs = Gson().fromJson(json, Array<MyClass>::class.java)
objs[0].name

Updated

You can also create extention function for that like this

suspend inline fun <reified T> ApplicationCall.safeReceive(): T {
    val json = this.receiveOrNull<String>()
    return Gson().fromJson(json, T::class.java)
}

then use it like this

val objs = call.safeReceive<Array<MyClass>>()
objs[0].name
Sabeeh
  • 1,478
  • 15
  • 15