Hi! I am struggeling with some serialization and w...
# serialization
d
Hi! I am struggeling with some serialization and was hoping somebody could help.. I want to pass in a list of objects as a body to a (ktor) request. This is where I’m doing the serialization.
Copy code
val userIds: List<MemberInput> = listOf(...)
val json: JsonElement = Json.nonstrict.toJson(MemberInput.serializer().list, userIds)
<http://client.post|client.post><HttpResponse> {
                header("Content-Type", "application/json")
                header("Accept", "*/*")
                body = json
}
This gives me an exception when setting it as the body to the request:
java.lang.ClassCastException: kotlinx.serialization.json.JsonObject cannot be cast to java.lang.String
. (I should be able to set the
userIds
as body out of the box, but for debugging purposes…) First; is this a kotlinx.serialization or a ktor issue? Secondly; what’s wrong? 🙂 I appreciate any help! 🙂
n
this seems a issue in how you use ktor also you can just serialize your object to a string and assign that to the body.. or let ktor handle the conversion, just need to register the json factory there..
Copy code
val client = HttpClient(HttpClientEngine) {
    install(JsonFeature) {
        serializer = KotlinxSerializer()
    }
}
like so
here is a full example that might be of help: https://ktor.io/clients/http-client/examples.html#example-json only that it uses gson, change that out and make the class a
@Serializable
and it should work
d
Thanks for your feedback. I have already installed the jsonFeature as you pointed out, and marked the data class with @Serializable. It always work when I’m parsing the result objects from the requests (“normal” objects and lists), and it works when serializing an object to the body of the request, but not when serializing a list of objects. Any idea why?
I can serialize it to a string, but then it will set the body as a String and not json, and the backend will fail to parse the body
n
try this for manually serialized things
d
Thanks! Will do and come back to you