【问题标题】:Moshi jason adapter with generic type具有通用类型的 Moshi jason 适配器
【发布时间】: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

 

【问题讨论】:

    标签: android kotlin moshi


    【解决方案1】:

    typeOfObject 已经是 Class&lt;T&gt; 类的一个实例,你不需要调用::class.java:它返回Class&lt;Class&gt;,这不是你想要的。

    只是改变

    val jsonAdapter: JsonAdapter<T> = moshi.adapter<T>(typeOfObject::class.java)
    

    val jsonAdapter: JsonAdapter<T> = moshi.adapter<T>(typeOfObject)
    

    顺便说一句:在每次反序列化时创建一个新的 Moshi 实例是次优的。你应该重复使用它。

    【讨论】:

    • 你是个传奇,非常感谢。
    猜你喜欢
    • 2018-02-21
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    相关资源
    最近更新 更多