Search code examples
ioskotlinkotlin-multiplatformkotlinx.serialization

Obtaining serializer from KClass is not available on native due to the lack of reflection


Description

I'm using Kotlinx serialization library in a multiplatform library for iOS and Android to handle HTTP requests. But I have this message when I'm using my request function on iOS, is there a workaround ? What line in my function is calling the unimplemented function ?

kotlin.NotImplementedError: An operation is not implemented: Obtaining serializer from KClass is not available on native due to the lack of reflection. Use .serializer() directly on serializable class.

To Reproduce

This is the function I wrote

@ImplicitReflectionSerializer
private suspend fun authenticationRequest(email: String, password: String): Either<ErrorMessage, Authentication> {
    return try {
        val response: Authentication = client.post {
            url("${Constants.API_URL}/security/login")
            body = jsonSerializer.write(LoginType(email, password))
        }
         Either.Right(response)
    } catch (e: ResponseException) {
        val message = Json.parse<ErrorMessage>(e.response.content.readUTF8Line() ?: "").apply {
            codeHttp = e.response.status.value
            reason = e.response.status.description
        }
        Either.Left(message)
    }
}

Environment

  • Kotlin version: 1.3.31

  • Kotlinx serialization version: 0.11.0

  • Kotlin platforms: iOS and Android

  • Gradle version: 5.1.1


Solution

  • I resolved the issue by myself. To make it work, I had to use setMapper when initialising KotlinxSerializer

    val serialiser = KotlinxSerializer(Json.nonstrict).apply {
            setMapper(Foo::class, Foo.serializer())
    }
    

    And when I call Json.parse(), the other signature of this function is useful

    Json.parse(ErrorMessage.serializer(), e.response.content.readUTF8Line() ?: "")