【发布时间】:2021-02-10 15:40:25
【问题描述】:
我想使用具有泛型类型的 Moshi 适配器。
这是我的泛型类型适配器代码,
fun <T> getObjectFromJson(typeOfObject: Class<T>, jsonString: String): T? {
val moshi = Moshi.Builder().build()
val jsonAdapter: JsonAdapter<T> = moshi.adapter<T>(
typeOfObject::class.java
)
return jsonAdapter.fromJson(jsonString)!!
}
此代码不起作用。它正在抛出一个错误,
平台类 java.lang.Class 需要显式注册 JsonAdapter
但是,如果我不使用这样的泛型,
fun getObjectFromJson(jsonString: String): UserProfile? {
val moshi = Moshi.Builder().build()
val jsonAdapter: JsonAdapter<UserProfile> = moshi.adapter<UserProfile>(
UserProfile::class.java
)
return jsonAdapter.fromJson(jsonString)!!
}
然后代码工作正常。
这是 UserProfile 类,
@Parcelize
@JsonClass(generateAdapter = true)
data class UserProfile(
@get:Json(name = "p_contact")
val pContact: String? = null,
@get:Json(name = "profile_pic")
var profilePic: String? = null,
@get:Json(name = "lname")
val lname: String? = null,
@get:Json(name = "token")
var token: String? = null,
@get:Json(name = "fname")
val fname: String? = null,
@SerializedName("_id")
@get:Json(name = "_id")
var id: String? = null,
@get:Json(name = "email")
var email: String? = null,
@SerializedName("refresh_token")
@get:Json(name = "refresh_token")
var refreshToken: String? = null
) : Parcelable
【问题讨论】: