https://kotlinlang.org logo
#ktor
Title
# ktor
r

robercoding

02/09/2023, 4:06 PM
Hello I'm using Ktor Client and I faced an issue that I don't know how to solve although I think I have some ideas on how to solve it Disclaimer: I don't know if I should post it here or #serialization 😅 There's an API that for the same parameter can return a
String
or a
List<String>
, if I get the response and use
response.body<MyClass>()
For instance this is
MyClass
Copy code
@Serializable
data class MyClass(
    val parameter: String // Could also be List<String>
)
Of course this fails to serialize because there's an illegal input, expect a specific type not both. This crashes when finds that there's some parameter in the json that is a
List<String>
I was thinking of ways to solve it, and the first thought was setting
Any
but, of course, breaks the serialisation laws. Then I thought that maybe I can do some custom deserialization but I don't wanna spend too much time shooting my shot in the dark. Do you know if that's the way or is there any other better approach?
a

Aleksei Tirman [JB]

02/09/2023, 4:54 PM
I would receive the body as a String or ByteArray and try to convert it twice by catching the serialization exception.
Or you can convert the body to JsonElement and check the type manually.
r

robercoding

02/09/2023, 4:57 PM
Beautiful,
JsonElement
removes any headache!! Thank you 😉
and try to convert it twice by catching the serialization exception.
Just curious, is there any example for this? I wonder how much effort would involve in doing this
a

Aleksei Tirman [JB]

02/09/2023, 6:42 PM
Never mind. I though that you need to convert to
List<MyClass>
or
MyClass
.
A custom converter would solve that problem.
🫶 1
🙏 1
8 Views