首页 > 解决方案 > RETROFIT 应为 BEGIN_ARRAY,但在第 1 行第 2 列路径 $ KOTLIN 处为 BEGIN_OBJECT

问题描述

嘿伙计们,我正在尝试从 API 获取数据。我可以使用这个https://raw.githubusercontent.com/atilsamancioglu/K21-JSONDataSet/master/crypto.json json 文件,但我不能让它工作。https://www.episodate.com/api/most-popular?page=1

这是我的主要活动

private fun loadData(){

    val retrofit = Retrofit.Builder()
            .baseUrl("https://www.episodate.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(MovieAPI::class.java)

    CoroutineScope(Dispatchers.IO).launch {
        val response = retrofit.getData()

        if (response.isSuccessful){
            response.body()?.let {
                Moviemodel = ArrayList(it)
            }
        }
        println(Moviemodel)

    }

我的数据类

data class MovieModel(
    val name: String
)

和 API 类

interface MovieAPI {
@GET("api/most-popular?page=1")
suspend fun getData(): Response<ArrayList<MovieModel>>

当我尝试 https://raw.githubusercontent.com/atilsamancioglu/K21-JSONDataSet/master/crypto.json这个文件时,我可以获取数据但是每当我尝试这个https://www.episodate.com/api/most-popular ?page=1应用程序崩溃。请看一下谢谢。

标签: javaandroidkotlinretrofitkotlin-coroutines

解决方案


如何使用 Retrofit 和 Gson 解析嵌套列表? 这是一个类似的问题。你的模型应该像

data class Movie(
    val page: Int,
    val pages: Int,
    val total: String,
    val tv_shows: List<TvShow>
)
data class TvShow(
    val country: String,
    val end_date: Any,
    val id: Int,
    val image_thumbnail_path: String,
    val name: String,
    val network: String,
    val permalink: String,
    val start_date: String,
    val status: String
)

然后API类

interface MovieAPI {
@GET("api/most-popular?page=1")
suspend fun getData(): Response<Movie>//instead of Response<ArrayList<Movie>>

在活动中

 CoroutineScope(Dispatchers.IO).launch {
        val response = retrofit.getData()

        if (response.isSuccessful){
            response.body()?.let {
                shows = List(it.tv_shows)
            }
        }
       for(show in shows){
       println(show.name) // here are the names
       }
    }

如果你想为你的模型使用不同的属性名,你应该用@SerializedName(). 更多信息请参考Gson:@Expose vs @SerializedName


推荐阅读