【问题标题】:Obtaining serializer from KClass is not available on native due to the lack of reflection由于缺少反射,从 KClass 获取序列化程序在本机上不可用
【发布时间】:2019-06-07 14:43:05
【问题描述】:

说明

我在 iOS 和 Android 的多平台库中使用 Kotlinx 序列化库来处理 HTTP 请求。但是当我在 iOS 上使用我的请求功能时,我收到了这条消息,有解决方法吗?我函数中的哪一行调用了未实现的函数?

kotlin.NotImplementedError: An operation is not implemented: 由于缺少反射,从 KClass 获取序列化程序在本机上不可用。直接在可序列化类上使用 .serializer()。

复制

这是我写的函数

@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)
    }
}

环境

  • Kotlin 版本:1.3.31

  • Kotlinx 序列化版本:0.11.0

  • Kotlin 平台:iOS 和 Android

  • Gradle 版本:5.1.1

【问题讨论】:

    标签: ios kotlin kotlin-multiplatform kotlinx.serialization


    【解决方案1】:

    我自己解决了这个问题。为了让它工作,我必须在初始化 KotlinxSerializer 时使用 setMapper

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

    当我调用 Json.parse() 时,这个函数的另一个签名很有用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-07
      • 2013-10-27
      • 2019-07-11
      • 1970-01-01
      相关资源
      最近更新 更多