https://kotlinlang.org logo
Title
c

CLOVIS

03/06/2020, 11:21 AM
Hi! I'm new at Ktor and kotlinx.serialization so this may be a very dumb question, sorry if that's the case... I'm trying to setup a multiplatform client to access some REST API. My example is an endpoint (
/account/auth/
) which I should send a JSON object to, which contains a field
username
and a field
password
. It should return a JSON object that contains a
token
field. I want to use Kotlinx.Serialization to generate the JSON objects, so I started with:
@Serializable
private data class ApiUsernamePassword(val username: String, val password: String)
and I do my request like this:
val client = HttpClient() {
    install(JsonFeature) {
        serializer = KotlinxSerializer()
    }
}

val res = <http://client.post|client.post><String> {
    url("<http://localhost:8000/account/auth/>")

    body = ApiUsernamePassword(username, password)
}
On the JVM, I get this error:
Companion
java.lang.NoSuchFieldError: Companion
	at io.ktor.client.features.json.serializer.KotlinxSerializer.<init>(KotlinxSerializer.kt:22)
(I can send the full stacktrace if needed) On JS, I get this error:
TypeError: Cannot read property 'plain' of undefined

    at new KotlinxSerializer (<http://localhost:9876/absolute/[REDACTED]/adapter-browser.js?fb6a5f1e12e8cc2bf794189b2b55f22def38ca94:157371:29>)
I've tried Googling it but I don't get any meaningul/related results for both of those errors... Did anyone encounter this before? I also tried adding an empty companion object to my serializable class but it didn't change anything. (all of the above is in the common module, if that's relevant)
g

gabin

03/06/2020, 11:39 AM
What version of ktor & serializable do you use?
c

CLOVIS

03/06/2020, 11:40 AM
Kotlin 1.3.70 Ktor 1.3.1 Serialization 0.20.0
g

gabin

03/06/2020, 11:42 AM
serialization 0.20.0 is not yet supported. Try 0.14.0
and kotlin 1.3.61
c

CLOVIS

03/06/2020, 11:44 AM
Ok, I'm trying
With your version changes I get (on the JVM):
Fail to send body. Content has type: class net.wildfyre.lib.ApiUsernamePassword (Kotlin reflection is not available), but OutgoingContent expected.
r

ribesg

03/06/2020, 11:57 AM
Add
contentType(ContentType.Application.Json)
before
body = …
c

CLOVIS

03/06/2020, 1:23 PM
@ribesg @gabin It works, thanks a lot!
👍 1