Android 具有泛型类型的Moshi jason适配器
我想使用具有泛型类型的Moshi适配器 这是我的泛型类型适配器代码Android 具有泛型类型的Moshi jason适配器,android,kotlin,moshi,Android,Kotlin,Moshi,我想使用具有泛型类型的Moshi适配器 这是我的泛型类型适配器代码 fun <T> getObjectFromJson(typeOfObject: Class<T>, jsonString: String): T? { val moshi = Moshi.Builder().build() val jsonAdapter: JsonAdapter<T> = moshi.adapter<T>( typeOfObject
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)!!
}
typeOfObject
已经是Class
类的一个实例,您正在调用::Class.java
,不需要:它返回Class
,这不是您想要的
换衣服
val-jsonAdapter:jsonAdapter=moshi.adapter(typeOfObject::class.java)
到
val-jsonAdapter:jsonAdapter=moshi.adapter(typeOfObject)
顺便说一下:在每次反序列化时创建一个新的Moshi实例是次优的。你应该重复使用它
fun getObjectFromJson(jsonString: String): UserProfile? {
val moshi = Moshi.Builder().build()
val jsonAdapter: JsonAdapter<UserProfile> = moshi.adapter<UserProfile>(
UserProfile::class.java
)
return jsonAdapter.fromJson(jsonString)!!
}
@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