安卓改造 - GET Json Array

问题描述 投票:0回答:1

当我在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.comwatch?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问题:----预期的是BEGIN_OBJECT,但在第1行是BEGIN_ARRAY。但我不知道自己错在哪里。请原谅我

谢谢你的热心帮助。

android json gson retrofit2
1个回答
2
投票

来自REST API的响应是一个数组,但你通过了 BikeStation 作为预期的响应类型。试着把它改成 Call<List<BikeStation>>,Callback<List<BikeStation>> 并改变返回类型 getJsonArrayData().

© www.soinside.com 2019 - 2024. All rights reserved.