微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

参数化类型的 Kotlin-Moshi 适配器

如何解决参数化类型的 Kotlin-Moshi 适配器

我有一个参数化的基类

@JsonClass(generateAdapter = true)
data class BaseResponse<T>(

    @Json(name = "message")
    val message: String?,@Json(name = "data")
    val data: T? = null
)

我想解析一个 JSON 字符串并获取 message

private inline fun <reified T> getMessage(): String? {
    return try {
        val jsonStr = "{\"message\":\"Email or password not provided\"}"
        val types = Types.newParameterizedType(
            BaseResponse::class.java,T::class.java
        )
        val moshiAdapter = moshi.Builder().build().adapter(types)
        val baseResponse = moshiAdapter.fromJson(jsonStr)
        baseResponse?.message
    } catch (exception: Exception) {
        null
    }
}

在适配器函数中出现编译错误

enter image description here

我如何调用这个函数

val str = getMessage<Any>()

解决方法

您没有指定您正在解析 BaseResponse,只需用此替换您的适配器创建

val moshiAdapter = Moshi.Builder().build().adapter<BaseResponse<T>>(types)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。