当我在onClick侦听器中调用getRetrofitArray()函数来获取JSon数组时,我发现应用程序崩溃了。
我的代码如下,请帮帮我:
public void getRetrofitArray() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitArrayAPI service = retrofit.create(RetrofitArrayAPI.class);
Call<BikeStation> call = service.getJsonArrayData();
call.enqueue(new Callback<BikeStation>() {
@Override
public void onResponse(Call<BikeStation> call, Response<BikeStation> response) {
Log.e("response ", response.body().toString());
Log.e("number ", response.body().getNumber().toString());
Log.e("address ", response.body().getAddress().toString());
Log.e("name ", response.body().getName().toString());
Log.e("banking ", response.body().getBanking().toString());
Log.e("bonus ", response.body().getBonus().toString());
Log.e("bike_stands ", response.body().getBike_stands().toString());
Log.e("available_bike_stands ", response.body().getAvailable_bike_stands().toString());
Log.e("available_bikes ", response.body().getAvailable_bikes().toString());
Log.e("status ", response.body().getStatus().toString());
Log.e("last_update ", response.body().getLast_update().toString());
}
@Override
public void onFailure(Call<BikeStation> call, Throwable t) {
Log.e("Error: ", t.toString());
}
});
}我关注了一个在线教程(https://www.youtube.com/watch?time_continue=2&v=T-XFHVEdTUA&feature=emb_logo),但没有太多的运气。我在logcat上看不到任何日志输出,除了
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $我使用的JSON数组具有以下结构:
[
{
"number": 42,
"contract_name": "dublin",
"name": "SMITHFIELD NORTH",
"address": "Smithfield North",
"position": {
"lat": 53.349562,
"lng": -6.278198
},
"banking": true,
"bonus": false,
"bike_stands": 30,
"available_bike_stands": 5,
"available_bikes": 25,
"status": "OPEN",
"last_update": 1589297754000
},
....我相信这个问题与Gson issue:- Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1非常相似,但我看不出哪里错了。请原谅我
谢谢你的帮助,
发布于 2020-05-15 04:29:13
来自REST API的响应是一个数组,但您将BikeStation作为预期的响应类型传递。尝试将其更改为Call<List<BikeStation>>,Callback<List<BikeStation>>,并在getJsonArrayData()中更改返回类型。
https://stackoverflow.com/questions/61806763
复制相似问题