2

Am trying to make an http post request but it is getting failed for reasons am not able to understand.

object KtorClient {
val client = HttpClient() {
    install(JsonFeature) {
        serializer = KotlinxSerializer()
    }
 }
}
suspend fun createOwner(url : String = "http://localhost:112/company/owner/register", ownerMapper: OwnerMapper) {
println(ownerMapper)
client.post<Unit>(url){
   body = ownerMapper
}
}

BlockquoteIllegalStateException {message_8yp7un$_0: "Fail to send body. Content has type: class OwnerMapper, but OutgoingContent expected.", cause_th0jdv$_0: null, stack: "captureStack↵Exception↵RuntimeException↵IllegalSta…↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵promiseReactionJob@[native code]", name: "IllegalStateException"}

After adding Serialization plugin, am getting this error:

"Can't locate argument-less serializer for class OwnerMapper. For generic classes, such as lists, please provide serializer explicitly."

I have followed the official example but not able to make it run. Am using Kotlin/Js and above error is coming from browser.

Tarun Chawla
  • 508
  • 4
  • 17

2 Answers2

1
    val client = HttpClient() {
        install(JsonFeature){
            serializer = KotlinxSerializer()
        }
    }
@Serializable
data class OwnerLoginMapper(
    val email: String? = null,
    val username: String? = null,
    val number: String? = null,
    val credential: String
)
@Serializable
data class Token(
    val token : String
)
var response = client.post<Token>(url){
    contentType(ContentType.Application.Json)
    body = ownerMapper
}
println(response.token)

Add these dependencies:

implementation("io.ktor:ktor-client-json-js:1.3.2")
implementation("io.ktor:ktor-client-serialization-js:1.3.2")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime-js:0.20.0")

Apply this plugin:

    kotlin("plugin.serialization") version "1.3.70"

PS: Choose appropriate version number.

Tarun Chawla
  • 508
  • 4
  • 17
0

Is your OwnerMapper class marked as @Serializable ?

If no -- please mark it as @Serializable

If yes -- could you please try to reproduce the second problem ("Can't locate argument-less serializer for class OwnerMapper. For generic classes, such as lists, please provide serializer explicitly.") without Ktor. To me it looks as a problem with serialization, probably some dependency is missing.

Please, also take a look at the github issue: https://github.com/Kotlin/kotlinx.serialization/issues/278

  • It is marked as serializable, currently am manually serializing instead of installing feature in ktor client. As manual serializatioj is working so I guess dependency are complete, it seems something wrong with ktor client. I will try to seperate out the problem and debug. – Tarun Chawla Jul 17 '20 at 02:34
  • @TarunChawla Can you attach a link to your project? – vanyochek Jul 17 '20 at 12:38
  • I was doing few things wrong here. I will post the answer to do it right way. – Tarun Chawla Jul 20 '20 at 12:07