[英]How to solve JSON retrofit error with Deferred Response
我跟隨着教程: 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 $*
我看着這個答案,但是我不知道如何使它適應我的代碼: 翻新預期為BEGIN_OBJECT,但為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
}
]
我已經有了列表,看不到如何糾正錯誤?
您必須將界面更新為:
interface LocationService {
@GET("locations?countryid=fr")
fun getLocationList() : Deferred<Response<List<Location>>>
}
另外,您不需要LocationResponse
類並刪除以下代碼:
data class LocationResponse (val results : List<Location>)
您期望得到響應並按如下方式進行解析:
{
"results": [
{ .. }
]
}
但是實際響應是這樣的:
[
{ .. }
]
該錯誤說明您期望在根目錄找到對象,但實際的json數據是array,因此您必須將其更改為array。
在您的API界面中,您正在定義getLocationList()方法以返回LocationResponse對象,而該API實際上返回的是對象列表,因此要解決此問題,請按以下方法進行定義。
interface LocationService {
@GET("locations?countryid=fr")
fun getLocationList() : Deferred<Response<List<Location>>>
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.