Lorenzo Battilocchi
Lorenzo Battilocchi

Reputation: 1178

Android Retrofit - GET Json Array

I see my app is crashing when I call getRetrofitArray() function in my onClick listener to get the JSon array.

My code is below, please help me:

  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());
        }
    });
}

I have followed an online tutorial (https://www.youtube.com/watch?time_continue=2&v=T-XFHVEdTUA&feature=emb_logo) but have not had much luck with it. I am not able to see any log output on logcat, except for

 java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

The JSON Array I'm using has the following structure:

[
{
"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
},
....

I believe this question is very similar to Gson issue:- Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1, but I can't see where I'm going wrong. Please forgive me,

Thank you for the kind help,

Upvotes: 2

Views: 410

Answers (1)

Gralls
Gralls

Reputation: 156

Response from REST API is an array but you passed BikeStation as a expected response type. Try change it to Call<List<BikeStation>>,Callback<List<BikeStation>> and change return type in getJsonArrayData().

Upvotes: 2

Related Questions