首页 > 解决方案 > 如何使用 Retrofit 和 RxJava 解析 json 数组

问题描述

我在使用 Retrofit + RxJava 解析对象数组时遇到问题

JSON 只包含这个数组

{
    "files": [
        {
            "id": 10,
            "notificationId": 15,
            "name": "cats.ncs",
            "dateTime": "2019-01-07T17:34:45"
        }
    ]
}

改装服务

@GET("/api/FileApi/files")
fun files(): Observable<FilesResponse>

FilesResponse 在哪里

data class FilesResponse(
    @SerializedName("files")
    var files: List<FileElement>
)

和 FileElement

data class FileElement(
    @SerializedName("id")
    var id: Long,
    @SerializedName("notificationId")
    var notificationId: Long,
    @SerializedName("name")
    var name: String,
    @SerializedName("dateTime")
    var dateTime: String
)

当我运行它时,我总是

CallObjectMethodA 的返回类型与 io.reactivex.Observable ApiService.files() 不匹配

那么如何解析只包含一个数组的 JSON 呢?

标签: kotlinretrofit2rx-java2

解决方案


尝试使用RxJava2 适配器

一体化

implementation 'com.squareup.retrofit2:adapter-rxjava2:{retrofit_version}'

改造客户端设置

new Retrofit.Builder()
  .baseUrl(BASE_URL)
  .addConverterFactory(GsonConverterFactory.create())
  .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) //option 1
  .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.newThread())) //option 2
  .build();

推荐阅读