【问题标题】:How to convert row JSON response into LiveData without using Room?如何在不使用 Room 的情况下将行 JSON 响应转换为 LiveData?
【发布时间】:2019-05-10 09:48:20
【问题描述】:

我卡在将 JSON 响应转换为 LiveData。这可以使用 Room 来实现。但我没有在我的应用中使用 Room。

private fun fetchFromNetwork(dbSource: LiveData<T>) {
    //here 'result' is MediatorLiveData
    result.addSource(dbSource) { newData -> result.setValue(Resource.loading(newData)) }
     createCall().enqueue(object : Callback<V> {
         override fun onResponse(call: Call<V>, response: Response<V>) {
             result.removeSource(dbSource)

          //   response.body() is JSON response from server and need tobe convert into LiveData type

             result.addSource(convertedLiveData) { newData ->
                 if (null != newData)
                     result.value = Resource.success(newData)
             }
         }

         override fun onFailure(call: Call<V>, t: Throwable) {
             result.removeSource(dbSource)
             result.addSource(dbSource) { newData ->
                 result.setValue(
                     Resource.error(
                         getCustomErrorMessage(t),
                         newData
                     )
                 )
             }
         }
     })
 }

【问题讨论】:

  • 您无法从 JSON 转换为 LiveData;您所能做的就是从 JSON 转换为实例,然后使用所述实例设置 LiveData 的值。并且没有办法用 Room 做任何事情,所以我不知道你为什么提到它。请查看Gson,这是一个可用于反序列化 JSON 数据的库。
  • 嗨@JulioE.RodríguezCabañas,感谢您的回复。我在这里提到“Room”是因为对“Android 架构组件”不熟悉,因为我已经经历了几个例子,我们可以从“Dao”获取 LiveData 类型的数据。请您提供代码 sn-p 使用 Gson 演示这一点吗?
  • 我不知道你想从 JSON 反序列化什么,但是 Gson 有很多文档并且非常易于使用。

标签: android android-room android-livedata android-mvvm


【解决方案1】:

我已将服务器的响应转换为 MutableLiveData,如下代码所示:

private fun fetchFromNetwork(dbSource: LiveData<T>) {
     result.addSource(dbSource) { newData -> result.setValue(Resource.loading(newData)) }
     createCall().enqueue(object : Callback<V> {
         override fun onResponse(call: Call<V>, response: Response<V>) {
             result.removeSource(dbSource)
            // here converting server response in to MutableLiveData
             val converted: MutableLiveData<T> = MutableLiveData()
             converted.value = response.body() as T
             result.addSource(converted) { newData ->
                 if (null != newData)
                     result.value = Resource.success(newData)
             }
         }

         override fun onFailure(call: Call<V>, t: Throwable) {
             result.removeSource(dbSource)
             result.addSource(dbSource) { newData ->
                 result.setValue(
                     Resource.error(
                         getCustomErrorMessage(t),
                         newData
                     )
                 )
             }
         }
     })
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-29
    • 2014-02-08
    • 1970-01-01
    • 2014-05-02
    • 2020-09-21
    • 1970-01-01
    相关资源
    最近更新 更多