如何解决参数化类型的 Kotlin-Moshi 适配器
@JsonClass(generateAdapter = true)
data class BaseResponse<T>(
@Json(name = "message")
val message: String?,@Json(name = "data")
val data: T? = null
)
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
}
}
val str = getMessage<Any>()
解决方法
您没有指定您正在解析 BaseResponse,只需用此替换您的适配器创建
val moshiAdapter = Moshi.Builder().build().adapter<BaseResponse<T>>(types)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。