Ashish Shrestha
Ashish Shrestha

Reputation: 71

Retrofit 2.0 get array of json object as a result of post request

I have a response form server as :

[
  {
    "ID": "1",
    "Title": "BIRATNAGAR",
    "BankID": "1",
    "BranchCode": "0",
    "LocationID": "71500200",
    "IsActive": "yes"
  },
  {
    "ID": "2",
    "Title": "BIRATNAGAR",
    "BankID": "1",
    "BranchCode": "0",
    "LocationID": "71500900",
    "IsActive": "yes"
  },
  {
    "ID": "3",
    "Title": "BIRATNAGAR",
    "BankID": "1",
    "BranchCode": "0",
    "LocationID": "94361117",
    "IsActive": "yes"
  }
]

I have retrofit api as: @POST("authapp/Restserver/api/Masterdata/getBranchListByBank") Call> getBranchListByBank(@Query("api_key") String id);

I have called it as: RetrofitArrayAPI service = retrofit.create(RetrofitArrayAPI.class);

    Call<List<BankBranch>> call = service.getBranchListByBank(s);

    call.enqueue(new Callback<List<BankBranch>>() {
        @Override
        public void onResponse(Call<List<BankBranch>> call, Response<List<BankBranch>> response) {
            try {

                List<BankBranch> banks = response.body();

                for (int i = 0; i < banks.size(); i++) {

                    String id  = banks.get(i).getTitle();
                    String name = banks.get(i).getID();
                    String marks = banks.get(i).getIsActive();
                    Log.i("ashihs", id + " " + marks + " " + name);


                }


            } catch (Exception e) {
                Log.d("onResponse", "There is an error");
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Call<List<BankBranch>> call, Throwable t) {
            Log.d("onFailure", t.toString());
        }

    });

But I cannot get the list of the bank branch. I get error as : java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

Can any one help me? Thanks in advance.

Upvotes: 2

Views: 1798

Answers (1)

Minis
Minis

Reputation: 462

U probably got bad Api request it schould look like this:

api:

@POST("authapp/Restserver/api/Masterdata/getBranchListByBank")
         Call<List<BankBranch>> getBranchListByBank(@Query("api_key") String id);

And the method schould look like this:

Call<List<BankBranch>> response = apiCall.getBranchListByBank(id);
            response.enqueue(new Callback<List<BankBranch>>() {
                @Override
                public void onResponse(Call<List<BankBranch>> call, Response<List<BankBranch>> response) {
                     List<BankBranch> bankBranch = response.body(); 
                }

                @Override
                public void onFailure(Call<List<BankBranch>> call, Throwable t) {

                }
            });
        }

make sure Your model BankBranch fit the JSON response;

Upvotes: 1

Related Questions