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
The typeOfObject is an instance of the Class<T> class already, you are calling ::class.java on it unnecessary: it returns Class<Class> and that's not what you want.
Just change
val jsonAdapter: JsonAdapter<T> = moshi.adapter<T>(typeOfObject::class.java)
to
val jsonAdapter: JsonAdapter<T> = moshi.adapter<T>(typeOfObject)
By the way: creating a new Moshi instance on each deserialization is suboptimal. You should reuse it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With