I want to use a Moshi adapter with a generic type.
Here is my generic type adapter code,
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)!!
}
This code is not working. It is throwing an error,
Platform class java.lang.Class requires explicit JsonAdapter to be registered
But, If I don’t use a generic type like this,
fun getObjectFromJson(jsonString: String): UserProfile? {
val moshi = Moshi.Builder().build()
val jsonAdapter: JsonAdapter<UserProfile> = moshi.adapter<UserProfile>(
UserProfile::class.java
)
return jsonAdapter.fromJson(jsonString)!!
}
Then the code is working fine.
Here is the UserProfile class,
@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