Gson不支持< model>Kotlin中的MutableLiveData

watbbzwu  于 2022-11-06  发布在  Kotlin
关注(0)|答案(1)|浏览(169)

我有下面的代码,当我从JSON反序列化对Gson的响应时,我收到了下面的异常:

java.lang.ClassCastException: com.test.model.photos.photosModel cannot be cast to androidx.lifecycle.MutableLiveData

这是我从服务器收到响应时的“我的代码”:

lateinit var _photosModel:MutableLiveData<photosModel>

  val gson = Gson()
            val modelObj = gson.fromJson<Any>(response.toString(), photosModel::class.java)
            _photosModel = modelObj as MutableLiveData<photosModel>
u59ebvdq

u59ebvdq1#

简单地说,因为您从Json解析到模型是Any,而您需要的是类型MutableLiveData
更重要的是,如果你想为MutableLiveData设置数据,你应该使用两个方法setValue(),如果你想在主线程中设置值,postValue(),如果你想在其他线程中设置值。
就这样:

  • 您的视图模型.kt*
private val _photosModel = MutableLiveData<PhotosModel>()
val photosModel: LiveData<PhotosModel> = _photosModel

val gson = Gson()
val modelObj: PhotosModel = gson.fromJson(response.toString(), PhotosModel::class.java) // You should make the first letter of the class uppercase.

// Set value for mutable livedata
_photosModel.value = modelObj

相关问题