如何使用 Retrofit 使用 GSON 解析来自 API 的 JSON 数组?

问题描述 投票:0回答:1

.嗨!

这是 API 响应:

[
    {
        "id": 1,
        "name": "Facebook"
    },
    {
        "id": 2,
        "name": "Angry Birds"
    }
]

这是我的 Retrofit API 声明:

  @GET("/api/apps")
  suspend fun getApps(): Response<AppList<App>>

这些是我的 App 和 AppList 类:

class App(

    var id: Number,
    var name: String

    ) : Serializable

class AppList<App>(list: List<App>)

这就是我调用 API 的方式:

 val response: Response<AppList<App>> = API.callBackend().getApplications()

这是错误:

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

如何使用 GSON 解析数组?我在这里缺少什么?

编辑:

如果我将所有

AppList<App>
更改为
List<App>
,我没有
IllegalException
,但我的 App 实例仍然绝对为空,这意味着
id
name
都是 null

android json kotlin gson
1个回答
-1
投票

方法签名应如下所示:

@GET("/api/apps")
suspend fun getApps(): List<App>
© www.soinside.com 2019 - 2024. All rights reserved.