https://kotlinlang.org logo
Title
d

darkmoon_uk

06/06/2019, 10:04 PM
How does one post an object via
HttpClient
that should be Json Encoded? Using iOS, if that matters, and I have the
JsonFeature
installed... but I get
kotlin.ClassCastException: example.model.Person cannot be cast to io.ktor.client.call.HttpClientCall
. Here's my code:
runBlocking {
            val client = HttpClient()

            val message = <http://client.post|client.post><Person> { //(path = "/path") {
                url("<http://localhost:8080/path>")
                contentType(ContentType.Application.Json)
                body = Person("James", "Smith")
            }
        }
...
Person
is
@Serializable
, should I not be setting it to the body of the post request like this? I assumed that, being
Any
,
JsonFeature
would know how to handle this? Can't find an example or details in ktor documentation.
m

Mike Dawson

06/07/2019, 6:29 AM
Kind new here too... but how did you install the JsonFeature? Did you try
val client = HttpClient() {
   install(JsonFeature)
}
Though there isn't a specific example for iOS, there is an example of setting a request body on a post request here: https://ktor.io/clients/http-client/call/requests.html Also, the code you shared seems to indicate you are expected a person as the response given by the server, so ktor would be trying to convert the response of the server to a Person. If the response of the server isn't a person, then that could cause a problem.
:tnx: 2
👍 2