【问题标题】:How to solve JSON retrofit error with Deferred Response如何使用延迟响应解决 JSON 改造错误
【发布时间】:2020-01-19 09:47:04
【问题描述】:

我跟着教程:https://android.jlelse.eu/android-networking-in-2019-retrofit-with-kotlins-coroutines-aefe82c4d777

我需要以JSON 格式恢复数据,我收到以下错误消息:

com.squareup.moshi.JsonDataException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at path $*

我查看了这个答案,但我不知道如何使其适应我的代码:Retrofit Expected BEGIN_OBJECT but was BEGIN_ARRAY

这是我的界面

interface LocationService {
    @GET("locations?countryid=fr")
    fun getLocationList() : Deferred<Response<LocationResponse>>
}

位置响应

data class LocationResponse (val results : List<Location>)

位置模型

data class Location (
    @field:Json(name = "id") val id : String,
    @field:Json(name = "category") val category : String,
    @field:Json(name = "label") val label : String,
    @field:Json(name = "value") val value : String
)

JSON 是这样的

[
  {
    "id":"city_39522",
    "category":"Villes",
    "label":"Parisot (81310)",
    "value":null
 },
 {
   "id":"city_36661",
   "category":"Villes",
   "label":"Paris 9ème (75009)",
   "value":null
 },
 {
   "id":"city_39743",
   "category":"Villes",
   "label":"Parisot (82160)",
   "value":null
 }
]

我已经得到一个列表,我不知道如何纠正错误?

【问题讨论】:

    标签: java android kotlin mvvm retrofit2


    【解决方案1】:

    在您的 API 接口中,您定义了 getLocationList() 方法以返回 LocationResponse 对象,而 API 实际上返回对象列表,因此要解决此问题,请按如下方式定义方法..

    interface LocationService {
        @GET("locations?countryid=fr")
        fun getLocationList() : Deferred<Response<List<Location>>>
    }
    

    【讨论】:

      【解决方案2】:

      您必须将界面更新为:

      interface LocationService {
          @GET("locations?countryid=fr")
          fun getLocationList() : Deferred<Response<List<Location>>>
      }
      

      您也不需要 LocationResponse 类并删除以下代码:

      data class LocationResponse (val results : List<Location>)
      

      您期待响应并像这样解析它:

      {
        "results": [
          { .. }
        ]
      }
      

      但实际反应是这样的:

       [
          { .. }
        ]
      

      错误说明您期望对象位于根目录,但实际的 json 数据是数组,因此您必须将其更改为数组。

      【讨论】:

      • @Asue 很高兴听到这个消息!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      • 2021-09-21
      • 2019-09-11
      相关资源
      最近更新 更多