JsonArray 到 Kotlin 数据 class 使用 Retrofit(预期 BEGIN_OBJECT 但实际是 BEGIN_ARRAY)

JsonArray to Kotlin data class using Retrofit (Expected BEGIN_OBJECT but was BEGIN_ARRAY)

我正在使用 Retrofit2

fun create(): MyApiService {

    return Retrofit.Builder()
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(BASE_URL)
                .build()
                .create(MyApiService::class.java)
}

隐式转换以下Json

[
    {
        "id": 1,
        "name": "John",
    }, {
        "id": 2,
        "name": "Mary",
    }
]

转化为 Kotlin 数据 class

object Model {
    data class Person(val id: Int, val name: String)
}

但是,我在尝试

时收到 Expected BEGIN_OBJECT but was BEGIN_ARRAY 错误
@GET("/people.json")
fun getPeople() : Observable<Model.Person>

我已经尝试更改 Model 对象以从 List 扩展(就像您通常在 Retrofit 1 中使用 Java 所做的那样)或创建一个 List 人员字段,但无济于事。

我发现我不必更改数据对象。

解决方案是简单地告诉调用方法检索 List 个模型而不是模型本身。

@GET("/people.json")
fun getPeople() : Observable<List<Model.Person>>

如何使用简单方法解决难题的经典示例。干得好,Retrofit !