首页 > 解决方案 > 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()
    }
}

我是根据https://itnext.io/kotlin-wrapping-your-head-around-livedata-mutablelivedata-coroutine-networking-and-viewmodel-b552c3a74eec完成 的修理它?

标签: androidkotlinmvvmgsonkotlin-coroutines

解决方案


您的响应返回 List 但您想检查单个对象值 (mBlogWrapper.name != null)。您的代码不需要此行。在示例中,他检查了“响应”是否不是“空”以及博客列表是否不为空。再次分析示例;)

如果您仍然有问题,请告诉我


推荐阅读