3

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

 
Antimonit
  • 2,846
  • 23
  • 34
Parag Rane
  • 179
  • 4
  • 15

1 Answers1

5

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.

Mafor
  • 9,668
  • 2
  • 21
  • 36