【问题标题】:JsonArray to Kotlin data class using Retrofit (Expected BEGIN_OBJECT but was BEGIN_ARRAY)使用 Retrofit 将 JsonArray 转换为 Kotlin 数据类(预期为 BEGIN_OBJECT 但为 BEGIN_ARRAY)
【发布时间】:2018-02-23 12:01:20
【问题描述】:

我正在使用 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 数据类

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 人员字段,但无济于事。

【问题讨论】:

    标签: android list kotlin retrofit2 rx-java2


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-14
      • 1970-01-01
      • 2019-05-10
      • 2016-09-26
      • 1970-01-01
      • 2017-02-14
      • 2020-07-26
      • 1970-01-01
      相关资源
      最近更新 更多