如何使用 Retrofit 和 Gson 解析嵌套列表? [英] How to parse nested List with Retrofit and Gson?

查看:103
本文介绍了如何使用 Retrofit 和 Gson 解析嵌套列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Gson 和 RxJava 做一个 Retrofit 教程,在某些时候它发出一个返回列表的 GET 请求,问题是我正在咨询的端点来自 TMDA,我想要的数据嵌套在里面一个 JsonObject,所以我对 Gson 和 Retrofit 很陌生,所以我不知道如何以解析嵌套列表中数据的方式配置构建器,因为本教程仅展示了它如何直接与列表一起工作,这是 RetrofitConfig 的代码:

I'm doing a Retrofit tutorial with Gson and RxJava and at some point it makes a GET request that returns a List, the thing is the endpoint that I'm consulting is from TMDA and the data that I want is nested inside a JsonObject, so I'm very new to Gson and Retrofit so I don't know how to config the builder in a way that it parses the data inside the nested List, since the tutorial only shows how it works directly with a List, this is the code of the RetrofitConfig:

   @GET("/3/discover/movie?api_key=${apiKey}&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1")
   fun getMovies(): Single<List<Movie>>
}

这是我的建造者:

 private val api = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .build()
        .create(MoviesApi::class.java)

    fun getMovies(): Single<List<Movie>> {
        return api.getMovies()
    }

这是 API 响应:

{
    "page": 1,
    "total_results": 10000,
    "total_pages": 500,
    "results": [
        {
            "popularity": 259.91,
            "vote_count": 366,
            "video": false,
            "poster_path": "/aQvJ5WPzZgYVDrxLX4R6cLJCEaQ.jpg",
            "id": 454626,
            "adult": false,
            "backdrop_path": "/qonBhlm0UjuKX2sH7e73pnG0454.jpg",
            "original_language": "en",
            "original_title": "Sonic the Hedgehog",
            "genre_ids": [
                28,
                35,
                878,
                10751
            ],
            "title": "Sonic the Hedgehog",
            "vote_average": 7.1,
            "overview": "Based on the global blockbuster videogame franchise from Sega, Sonic the Hedgehog tells the story of the world’s speediest hedgehog as he embraces his new home on Earth. In this live-action adventure comedy, Sonic and his new best friend team up to defend the planet from the evil genius Dr. Robotnik and his plans for world domination.",
            "release_date": "2020-02-12"
        },
        {
            "popularity": 253.357,
            "vote_count": 4333,
            "video": false,
            "poster_path": "/7IiTTgloJzvGI1TAYymCfbfl3vT.jpg",
            "id": 496243,
            "adult": false,
            "backdrop_path": "/TU9NIjwzjoKPwQHoHshkFcQUCG.jpg",
            "original_language": "ko",
            "original_title": "기생충",
            "genre_ids": [
                35,
                18,
                53
            ],
            "title": "Parasite",
            "vote_average": 8.6,
            "overview": "All unemployed, Ki-taek's family takes peculiar interest in the wealthy and glamorous Parks for their livelihood until they get entangled in an unexpected incident.",
            "release_date": "2019-05-30"
        },
        {
            "popularity": 213.161,
            "vote_count": 2415,
            "video": false,
            "poster_path": "/xBHvZcjRiWyobQ9kxBhO6B2dtRI.jpg",
            "id": 419704,
            "adult": false,
            "backdrop_path": "/5BwqwxMEjeFtdknRV792Svo0K1v.jpg",
            "original_language": "en",
            "original_title": "Ad Astra",
            "genre_ids": [
                12,
                18,
                9648,
                878,
                53
            ],
            "title": "Ad Astra",
            "vote_average": 6,
            "overview": "The near future, a time when both hope and hardships drive humanity to look to the stars and beyond. While a mysterious phenomenon menaces to destroy life on planet Earth, astronaut Roy McBride undertakes a mission across the immensity of space and its many perils to uncover the truth about a lost expedition that decades before boldly faced emptiness and silence in search of the unknown.",
            "release_date": "2019-09-17"
        },
        {
            "popularity": 171.658,
            "vote_count": 776,
            "video": false,
            "poster_path": "/h4VB6m0RwcicVEZvzftYZyKXs6K.jpg",
            "id": 495764,
            "adult": false,
            "backdrop_path": "/uozb2VeD87YmhoUP1RrGWfzuCrr.jpg",
            "original_language": "en",
            "original_title": "Birds of Prey (and the Fantabulous Emancipation of One Harley Quinn)",
            "genre_ids": [
                28,
                35,
                80
            ],
            "title": "Birds of Prey (and the Fantabulous Emancipation of One Harley Quinn)",
            "vote_average": 6.8,
            "overview": "After her breakup with the Joker, Harley Quinn joins forces with singer Black Canary, assassin Huntress, and police detective Renee Montoya to help a young girl named Cassandra, who had a hit placed on her after she stole a rare diamond from crime lord Roman Sionis.",
            "release_date": "2020-02-05"
        },
        {
            "popularity": 154.297,
            "vote_count": 2258,
            "video": false,
            "poster_path": "/pThyQovXQrw2m0s9x82twj48Jq4.jpg",
            "id": 546554,
            "adult": false,
            "backdrop_path": "/cjTQSwcsfVdirSFSHNBXRGkxmWa.jpg",
            "original_language": "en",
            "original_title": "Knives Out",
            "genre_ids": [
                35,
                80,
                18,
                9648,
                53
            ]

对于更多的电影来说都是这样,所以我配置它的方式我收到了 JsonObject 但它期待一个 List 所以它给出了错误:

It goes like that for more movies, so the way I have it configurated I receive the JsonObject but it is expecting a List so it gives the error:

 Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

因此,对于如何解决此问题的任何想法将不胜感激,我对这些主题很陌生,因此提前道歉.

So any ideas on how to solve this would be very appreciated, I'm very new to these topics so sorry in advance.

这是我的模型,因为有人问过

Here is my model since someone asked

data class Movie(
    val page: Int?,
    val total_results: Int?,
    val total_pages: Int?,
    val results: List<MovieData>
)

data class MovieData(
    val popularity: Int?,
    val vote_count: Int?,
    val video: Boolean?,
    val poster_path: String?,
    val id: Int?,
    val adult: Boolean?,
    val backdrop_path: String?,
    val original_language: String?,
    val original_title: String?,
    val genre_ids: List<Int>?,
    val title: String?,
    val vote_average: Int?,
    val overview: String?,
    val release_date: String?
)

推荐答案

基本上,当您尝试将其解析为 JSON 数组时,您的响应是一个 JSON 对象.您的模型类 Movie 是您得到的响应.所以如果你想要完整的响应使用

Basically your response is a JSON Object while you are trying to parse it as an JSON Array. Your Model class Movie is the response your get. So if you want the complete response use

fun getMovies(): Single<Movie>

这将为您提供完整的响应,其中包含 results: List 的值以及返回的其他参数.

this will give you the complete response, with the value of results: List<MovieData> within it alongwith other parameters returned.

希望能帮到你

这篇关于如何使用 Retrofit 和 Gson 解析嵌套列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆