Home > Net >  Moshi: Expected BEGIN_ARRAY but was BEGIN_OBJECT at path
Moshi: Expected BEGIN_ARRAY but was BEGIN_OBJECT at path

Time:04-27

I get the following error from Moshi: Expected BEGIN_ARRAY but was BEGIN_OBJECT at path This is my interface:

interface ApiService {
    @GET("movie/popular")
    suspend fun getTopRatedMovies(
        @Query("api_key") apiKey: String = BuildConfig.API_KEY,
        @Query("page") page: Int = 1
    ): List<TopRatedMovies>

data class

data class TopRatedMovies(
    @Json(name = "title") val title: String,
    @Json(name = "poster_path") val posterPath: String,
)

The response looks like this: enter image description here

I know that there are some other questions with the same title but those didn't help me.

CodePudding user response:

From the function's return type (List<TopRatedMovies>), Moshi is expecting your API to return a list, but it's returning an object ({"page": ..., "results": [...]}) instead.

To handle this, you can create a TopRatedMoviesPage class like this:

data class TopRatedMoviesPage(
    @Json(name = "page") val page: Int,
    @Json(name = "results") val results: List<TopRatedMovies>,
)

And change your API definition to this:

@GET("movie/popular")
suspend fun getTopRatedMovies(
    @Query("api_key") apiKey: String = BuildConfig.API_KEY,
    @Query("page") page: Int = 1
): TopRatedMoviesPage
  • Related