简体   繁体   English

如何使用延期响应解决JSON改装错误

[英]How to solve JSON retrofit error with Deferred Response

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

I need to recover data in JSON format, I get the following error message : 我需要恢复JSON格式的数据,出现以下错误消息:

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

I looked at this answer but I don't know how to adapt it to my code : Retrofit Expected BEGIN_OBJECT but was BEGIN_ARRAY 我看着这个答案,但是我不知道如何使它适应我的代码: 翻新预期为BEGIN_OBJECT,但为BEGIN_ARRAY

This is my interface 这是我的界面

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

LocationResponse 位置响应

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

Location Model 位置模型

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
)

The JSON is like this 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
 }
]

I'm already getting a list, I don't see how to correct the error ? 我已经有了列表,看不到如何纠正错误?

You have to update your interface as: 您必须将界面更新为:

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

Also you don't need LocationResponse class and remove the below code: 另外,您不需要LocationResponse类并删除以下代码:

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

You are expecting the response and parsing it like this: 您期望得到响应并按如下方式进行解析:

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

But Actual response is like this: 但是实际响应是这样的:

 [
    { .. }
  ]

The error explains that you are expecting object at the root but actual json data is array, so you have to change it to array. 该错误说明您期望在根目录找到对象,但实际的json数据是array,因此您必须将其更改为array。

In your API interface you're defining getLocationList() method to return a LocationResponse object whereas the API actually returns a list of objects, so to fix this define the method as follows.. 在您的API界面中,您正在定义getLocationList()方法以返回LocationResponse对象,而该API实际上返回的是对象列表,因此要解决此问题,请按以下方法进行定义。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM