预期 BEGIN_ARRAY 但在路径 $ BEGIN_OBJECT
Expected BEGIN_ARRAY but was BEGIN_OBJECT at path $
Interface
Json file looks like that
Error
Trying to retrieve these
interface StationService {
@GET("/bus/nearstation/latlon/[lat]/[lon]/[distance].json")
suspend fun getStationData(): Response<List<Station>>
}
.
答案 1 更改后:
for (station in it) {
stationNames.append(station.street_name)
.append("\n")
}
在 MainFragment.kt 中出现此错误:
For 循环范围必须有一个 'iterator()' 方法
根据您需要 Class 包装的响应结构 List<Station>
:应用以下更改:
data class ResponseData(
@SerializedName("data") val data: NearestStation
)
data class NearestStation(
@SerializedName("nearststations") val nearestStations: List<Station>
)
该站与您现在拥有的数据相同 class。现在更改改装服务如下:
interface StationService {
@GET("/bus/nearstation/latlon/[lat]/[lon]/[distance].json")
suspend fun getStationData(): Call<ResponseData>
}
为什么?
JSON 对象中的根对象由两个字段组成:code
类型的字符串(从示例绕过)和 data
对象由一个名为 neareststations
的字段组成电台列表。您需要在数据 class 模型中遵循相同的对象结构。
---编辑:
您需要在代码中更改以下内容:
如果您对改造服务进行了我提到的更改,则需要更改类型
val stationData = MutableLiveData<List<Station>>()
到
val stationData = MutableLiveData<ResponseData>()
并更改
val serviceData = service.getStationData().body()
进入
val serviceData = service.getStationData().execute().body()
```.
Pay attention that ```serviceData`` is from type ```ResponseData``` not ```List``` So replace ```?: emptyList()``` with mocked ```ResponseData```
Interface
Json file looks like that
Error
Trying to retrieve these
interface StationService {
@GET("/bus/nearstation/latlon/[lat]/[lon]/[distance].json")
suspend fun getStationData(): Response<List<Station>>
}
.
答案 1 更改后:
for (station in it) {
stationNames.append(station.street_name)
.append("\n")
}
在 MainFragment.kt 中出现此错误: For 循环范围必须有一个 'iterator()' 方法
根据您需要 Class 包装的响应结构 List<Station>
:应用以下更改:
data class ResponseData(
@SerializedName("data") val data: NearestStation
)
data class NearestStation(
@SerializedName("nearststations") val nearestStations: List<Station>
)
该站与您现在拥有的数据相同 class。现在更改改装服务如下:
interface StationService {
@GET("/bus/nearstation/latlon/[lat]/[lon]/[distance].json")
suspend fun getStationData(): Call<ResponseData>
}
为什么?
JSON 对象中的根对象由两个字段组成:code
类型的字符串(从示例绕过)和 data
对象由一个名为 neareststations
的字段组成电台列表。您需要在数据 class 模型中遵循相同的对象结构。
---编辑:
您需要在代码中更改以下内容:
如果您对改造服务进行了我提到的更改,则需要更改类型
val stationData = MutableLiveData<List<Station>>()
到
val stationData = MutableLiveData<ResponseData>()
并更改
val serviceData = service.getStationData().body()
进入
val serviceData = service.getStationData().execute().body()
```.
Pay attention that ```serviceData`` is from type ```ResponseData``` not ```List``` So replace ```?: emptyList()``` with mocked ```ResponseData```