android - Kotlin Json 解析 MVVM
问题描述
我正在尝试学习使用协程将 Json 解析为 MVVM 中的 Recyclerview 的 MVVM 架构。但是我在 BlogRepository 类上遇到错误。
我的 Json 文件如下所示:
[
{
"id": 1,
"name": "potter",
"img": "https://images.example.com/potter.jpg"
},
{ …}
]
我创建了如下数据类:
@JsonClass(generateAdapter = true)
class ABCCharacters (
@Json(name = "id") val char_id: Int,
@Json(name = "name") val name: String? = null,
@Json(name = "img") val img: String
)
然后 RestApiService 如下:
interface RestApiService {
@GET("/api")
fun getPopularBlog(): Deferred<List<ABCCharacters>>
companion object {
fun createCorService(): RestApiService {
val okHttpClient = OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.MINUTES)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.build()
return Retrofit.Builder()
.baseUrl("https://example.com")
.addConverterFactory(MoshiConverterFactory.create())
.client(okHttpClient)
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.build().create(RestApiService::class.java)
}
}
}
博客Reposity.kt
class BlogRepository() {
private var character = mutableListOf<ABCCharacters>()
private var mutableLiveData = MutableLiveData<List<ABCCharacters>>()
val completableJob = Job()
private val coroutineScope = CoroutineScope(Dispatchers.IO + completableJob)
private val thisApiCorService by lazy {
RestApiService.createCorService()
}
fun getMutableLiveData():MutableLiveData<List<ABCCharacters>> {
coroutineScope.launch {
val request = thisApiCorService.getPopularBlog()
withContext(Dispatchers.Main) {
try {
val response = request.await()
val mBlogWrapper = response;
if (mBlogWrapper != null && mBlogWrapper.name != null) {
character = mBlogWrapper.name as MutableList<ABCCharacters>
mutableLiveData.value=character;
}
} catch (e: HttpException) {
// Log exception //
} catch (e: Throwable) {
// Log error //)
}
}
}
return mutableLiveData;
}
}
最后是 ViewModel 类
class MainViewModel() : ViewModel() {
val characterRepository= BlogRepository()
val allBlog: LiveData<List<ABCCharacters>> get() = characterRepository.getMutableLiveData()
override fun onCleared() {
super.onCleared()
characterRepository.completableJob.cancel()
}
}
解决方案
您的响应返回 List 但您想检查单个对象值 (mBlogWrapper.name != null)。您的代码不需要此行。在示例中,他检查了“响应”是否不是“空”以及博客列表是否不为空。再次分析示例;)
如果您仍然有问题,请告诉我
推荐阅读
- python - Django 休息框架 - 返回图像作为响应
- mysql - Mysql连接错误:错误:数据包乱序。得到:45 预期:0
- c# - PHP 和 C# 中的不同 MD5 哈希值
- java - 服务器发送事件,空指针
- php - Eclipse Oxygen.3:克隆存储库时的问题
- apache-spark - 在运行时在 Spark 中获取 NodeID
- python - 在python中生成一定范围内一定间隔的Lat-Long对矩阵
- php - 使用 CSV 将数据发布到 MySQL 数据库 PHP
- python - Kubernetes - Configuring Angular to Work with a Backend API
- python - 当我编译我的python代码时,我得到:RecursionError:调用Python对象时超出了最大递归深度