https://kotlinlang.org logo
Title
s

Sourabh Rawat

07/18/2021, 8:48 PM
How does ktor serialize
body
, which is of type
Any
? When I do something like this, it fails..
@Serializable
class Foo(val bar: String)

@Test
fun test() {
    val any: Any = Foo("asd")
    Json.encodeToString(any).also { println(it) }
}
a

Aleksei Tirman [JB]

07/19/2021, 12:22 PM
Could you please share a code with Ktor involved?
s

Sourabh Rawat

07/19/2021, 7:06 PM
private suspend inline fun <reified V> MethodData.call(): V {
        return <http://httpClient.post|httpClient.post> {
            url(endpoint(token, id))
            contentType(ContentType.Application.Json)
            body = this@call
        }
    }
above has
body
type of
Any
MethodData
is interface. I call
call
method on subclasses of
MethodData
but in the scope of
call
it is denoted by
MethodData
. I believe same thing is happening in my above code. But it is failing for my code, where as ktor is able to encode the body.
a

Aleksei Tirman [JB]

07/20/2021, 8:17 AM
There is a method HttpClient.defaultTransformers that creates an instance of
OutgoingContent
object depending on a body's actual type.
s

Sourabh Rawat

07/20/2021, 8:19 AM
Won’t it evaluate to
content = null
since
ContentType
is neither
Plain/ByteArray/ByteReadChannel
?
a

Aleksei Tirman [JB]

07/20/2021, 8:27 AM
If you have the
JsonFeature
installed then it will return TextContent object earlier (a serializer will be determined on this line).
s

Sourabh Rawat

07/20/2021, 1:13 PM
Ah I see. Now I get it. Thanks a lot!