为什么在 android studio 中使用 gson 解析 json 对象时得到空值?

Why am I getting null values when using gson to parse a json object in android studio?

我正在阅读以下内容 JSON 并使用 GSON 将其转换为一个对象,然后我可以使用该对象访问所述对象的属性以帮助在我的应用程序中显示图像。

但是我想使用的字段之一 imageURL 返回空值。查看json(下面的link)我们可以清楚地看到它不是空的。

https://api.letsbuildthatapp.com/youtube/home_feed

我已经使用调试器演示了我为每个 imageURL 获取的空值:

Debugger output

所以该对象为我提供了 imageURL 的空值,但 link 不是。怎么回事?

这是我编写的用于获取和解析 JSON 对象的函数:

private fun fetchJson() {
        println("Attempting to fetch JSON")

        val url = "https://api.letsbuildthatapp.com/youtube/home_feed"
        val request = Request.Builder().url(url).build()
        val client = OkHttpClient()

        client.newCall(request).enqueue(object : Callback {
            override fun onResponse(call: Call, response: Response) {
                val body = response.body?.string()
                println(body)

                val gson = GsonBuilder().create()

                val homeFeed = gson.fromJson(body, HomeFeed::class.java)

                runOnUiThread {
                    recyclerView_main.adapter = MainAdapter(homeFeed)
                }
            }

            override fun onFailure(call: Call, e: IOException) {
                println("failed to execute request")
            }
        }
         )

    }

我的 HomeFeed class 是这样的:


class HomeFeed(val videos: List<Video>)

class Video(val id: Int, val name: String, val link: String, val imageURL: String, numberOfViews: Int,
            val channel: Channel)

class Channel(val name: String, val profileImageUrl: String)

我相信这应该足够详细了,但如果需要更多信息,请告诉我。

谢谢。

试试这个对象,你应该为 vals 使用相同的名称,"imageUrl" 而不是 "imageURL":

data class HomeFeed(
    val user: User,
    val videos: List<Video>
)

data class User(
    val id: Int,
    val name: String,
    val username: String
)

data class Video(
    val channel: Channel,
    val id: Int,
    val imageUrl: String,
    val link: String,
    val name: String,
    val numberOfViews: Int
)

data class Channel(
    val name: String,
    val numberOfSubscribers: Int,
    val profileImageUrl: String
)