【发布时间】:2021-09-23 19:14:56
【问题描述】:
我想检索一个 JSON 数组,我该如何调整我的代码库。我使用了改造库来检索数据,并使用了 MVVM 架构。我收到错误 Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $.
这是我的端点类:
@GET("v2/venues/search")
fun fetchAllVenues(): Call<List<Venue>>
}
这是我的存储库类:
class VenueRepository {
private var apiInterface: VenuesEndpoint? = null
init {
apiInterface = ApiClient.getApiClient().create(VenuesEndpoint::class.java)
}
fun fetchAllVenues(): MutableLiveData<List<Venue>?> {
val data = MutableLiveData<List<Venue>?>()
apiInterface?.fetchAllVenues()?.enqueue(object : Callback<List<Venue>> {
override fun onFailure(call: Call<List<Venue>>, t: Throwable) {
data.value = null
}
override fun onResponse(
call: Call<List<Venue>>,
response: Response<List<Venue>>
) {
val res = response.body()
if (response.code() == 200 && res != null) {
data.value = res
} else {
data.value = null
}
}
})
return data
}
}
这是我的模型类:
data class Venue(var id:Int,var name:String)
这是我的视图模型类:
class VenueViewModel : ViewModel() {
private var venueRepository: VenueRepository? = null
var postModelListLiveData: MutableLiveData<List<Venue>?>? = null
init {
venueRepository = VenueRepository()
postModelListLiveData = MutableLiveData()
}
fun fetchAllVenues() {
postModelListLiveData = venueRepository?.fetchAllVenues()
}
}
这是我要检索的 JSON:
"response": { "venues": [ { "id": "4b83cb72f964a520d71031e3" "name": "Stadhuis" "contact": { "phone": "+3114010" "formattedPhone": "+31 14010" "twitter": "rotterdam" } "location": { "address": "Coolsingel 40" "lat": 51.92258962728412 "lng": 4.480227190204032 "labeledLatLngs": [ "0": { "label": "display" "lat": 51.92258962728412 "lng": 4.480227190204032 } ] "postalCode": "3011 AD" "cc": "NL" "city": "Rotterdam" "state": "Zuid-Holland" "country": "Nederland" "formattedAddress": [ "0": "Coolsingel 40" "1": "3011 AD Rotterdam" "2": "Nederland"
【问题讨论】:
-
你能分享一下json的样子吗?
-
"response": { "venues": [ { "id": "4b83cb72f964a520d71031e3" "name": "Stadhuis" "contact": { "phone": "+3114010" "formattedPhone": "+31 14010" "twitter": "鹿特丹" } "location": { "address": "Coolsingel 40" "lat": 51.92258962728412 "lng": 4.480227190204032 "labeledLatLngs": [ "0": { "label": "display" "lat": 51.92258962728412 "lng": 4.480227190204032 } ] "postalCode": "3011 AD" "cc": "NL" "city": "Rotterdam" "state": "Zuid-Holland" "country": “Nederland”“formattedAddress”:[“0”:“Coolsingel 40”“1”:“3011 AD Rotterdam”“2”:“Nederland”]}
-
您可以更新您的问题并包含 json
标签: android arrays kotlin mvvm retrofit