Hello :face_with_peeking_eye: Receive and use exte...
# ktor
h
Hello 🫣 Receive and use external APIs and have different data types coming in Naturally, I got serialisation Error This may not be specific to KTOR, but I'm using it. REST API and WEBSOCKET API are currently handled in this way. It's a bit hard-coded and weird. Is there a better way? REST API Case : I'm taking data as a JsonElement type, filtering it and convert it back to the data class type with decodeFromJsonElement. Like this
val rawText = rawResponse.text
._filterKeys_ *{ it* != "text" *}*
._mapValues_ *{*
_defaultJson_._decodeFromJsonElement_<TextResponse>(*it*.value)
}
Websocket API Case : I’m taking data as a Text type, filtering it and convert it back to the data class type with decodeFromString. Like this
val json = *it*._readText_()
if (json._contains_("text")) {
_defaultJson_.decodeFromString<TextResponse>(json)
} else null
I was thinking of creating multiple data classes for a single call, but I don't know how to do this either. If you have a way to do this, please let me know the keywords!
s
I personally use something like this.
Copy code
val request = kotlin.runCatching { call.receiveNullable<YourDataClass>() }.getOrNull() ?: kotlin.run {
    call.respond(HttpStatusCode.BadRequest)
    return@post
}
This will automatically convert the Json object to your data class specified in "call.receiveNullable<*YourDataClass*>()" and if the Json object is empty or does not conform to the data class, it will reject it, so keep that in mind. You can access it by using the "request" variable. I don't know much about Websockets or multible data classes per call so I cant help you there.
❤️ 1