【问题标题】:How to parse json array with Retrofit and RxJava如何使用 Retrofit 和 RxJava 解析 json 数组
【发布时间】:2019-01-07 19:46:38
【问题描述】:

我在使用 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>
)

和文件元素

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 呢?

【问题讨论】:

  • 显示你如何称呼它

标签: kotlin retrofit2 rx-java2


【解决方案1】:

尝试使用RxJava2 Adapter

集成

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();

【讨论】:

    【解决方案2】:

    几点说明

    首先,您可能需要向我们展示您如何称呼ApiService.files()

    可能出了什么问题

    如何称呼

    可能的解决方案是什么

    像这样调用方法

    ApiService
            .files()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                // Handle the values here
            },{
                // Handle the error here
            },{
                // Handle the completion here (optional)
            })
    

    不是这样的

    ApiServices.files()
    

    也没有

    var fileResponse = ApiServices.files()
    

    如上所述,确保您已正确设置改造构建器

    • RxJava2CallAdapterFactory
    • GsonConverterFactory

    除此之外,如果没有您如何调用它的代码,我们将无法深入帮助您。

    【讨论】:

      猜你喜欢
      • 2016-01-11
      • 2015-12-05
      • 2021-01-17
      • 1970-01-01
      • 1970-01-01
      • 2020-04-15
      • 2015-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多