作为post请求的结果,Retrofit 2.0获取json对象的数组

时间:2016-09-26 10:52:27

标签: java android retrofit

我有一个响应表单服务器:

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

我改装api为:   @POST(" authapp / Restserver / API / Masterdata / getBranchListByBank&#34)     呼叫> getBranchListByBank(@Query(" api_key")String id);

我称之为:  RetrofitArrayAPI服务= 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());
        }

    });

但我无法获得银行分行的名单。我得到错误: java.lang.IllegalStateException:预期为BEGIN_ARRAY,但在第1行第2列路径为BEGIN_OBJECT $

任何人都可以帮助我吗? 提前谢谢。

1 个答案:

答案 0 :(得分:1)

你可能得到了很糟糕的Api请求它应该是这样的:

api:

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

方法应该是这样的:

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) {

                }
            });
        }

确保您的模型BankBranch符合JSON响应;