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

Hen*_*usa 1 android list kotlin retrofit2 rx-java2

我正在使用Retrofit2

fun create(): MyApiService {

    return Retrofit.Builder()
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(BASE_URL)
                .build()
                .create(MyApiService::class.java)
}
Run Code Online (Sandbox Code Playgroud)

隐式转换以下Json

[
    {
        "id": 1,
        "name": "John",
    }, {
        "id": 2,
        "name": "Mary",
    }
]
Run Code Online (Sandbox Code Playgroud)

进入Kotlin数据类

object Model {
    data class Person(val id: Int, val name: String)
}
Run Code Online (Sandbox Code Playgroud)

但是,我Expected BEGIN_OBJECT but was BEGIN_ARRAY在尝试时遇到错误

@GET("/people.json")
fun getPeople() : Observable<Model.Person>
Run Code Online (Sandbox Code Playgroud)

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

Hen*_*usa 7

我发现我没有必要更改数据对象.

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

@GET("/people.json")
fun getPeople() : Observable<List<Model.Person>>
Run Code Online (Sandbox Code Playgroud)

使用简单方法解决难题的典型示例.做得好,Retrofit!