如何使用延期响应解决JSON改装错误 [英] How to solve JSON retrofit error with Deferred Response
问题描述
我遵循了教程: https: //android.jlelse.eu/android-networking-in-2019-retrofit-with-kotlins-coroutines-aefe82c4d777
我需要恢复JSON
格式的数据,我收到以下错误消息:
I need to recover data in JSON
format, I get the following error message :
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
这是我的界面
interface LocationService {
@GET("locations?countryid=fr")
fun getLocationList() : Deferred<Response<LocationResponse>>
}
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
}
]
我已经有了列表,看不到如何纠正错误?
I'm already getting a list, I don't see how to correct the error ?
推荐答案
您必须将界面更新为:
interface LocationService {
@GET("locations?countryid=fr")
fun getLocationList() : Deferred<Response<List<Location>>>
}
此外,您不需要 LocationResponse
类并删除以下代码:
Also you don't need LocationResponse
class and remove the below code:
data class LocationResponse (val results : List<Location>)
您期望得到响应并按如下方式对其进行解析:
{
"results": [
{ .. }
]
}
但是实际响应是这样的:
[
{ .. }
]
该错误说明您期望在根目录找到对象,但是实际的json数据是array,因此您必须将其更改为array.
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改装错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!