Kotlin - Optional Generic response in Ktor

35 views Asked by At

I have the following model for an api response:

@Serializable
public data class Response<out T>(
    val code: String,
    val message: String,
    val data: T? = null,
)

The thing is that the data field is optional. Therefore when I receive the full, it works fine. Full response being something like this:

{
"code":"code-sample",
"message":"This is a sample message",
"data": { ... }
}

BUT if I receive a body like this:

{
"code":"code-sample",
"message":"This is a sample message"
}

I receive the follwoing error message:

Captured type parameter T from generic non-reified function. Such functionality cannot be supported because T is erased, either specify serializer explicitly or make calling function inline with reified T.

So, how can I have a model that can be read with an optional generic like this? My Json configuration is as such:

Json {
  ignoreUnknownKeys = true
  encodeDefaults = true
}
0

There are 0 answers