How to handle object on onResponse of retrofit 2.0

会有一股神秘感。 提交于 2019-12-08 06:09:37

问题


This is my logic for getting response in retrofit 2.0

call.enqueue(new Callback<ArrayList<Wallet>>() {
  @Override
  public void onResponse(Response<ArrayList<Wallet>> response, Retrofit retrofit) {

      if (response.isSuccess()) {
          // use response data and do some fancy stuff :)
         loading.dismiss();
          ArrayList<Wallet> orders = response.body();
          Utility.displayToast("Wallet size is" + orders.size());

      } else {

      }
  }

});


Data format from rest API is like this:

[
{
  "description": "Cashback",
  "amount": "20.00",
  "type": "1",
  "date": "11/03/2016"
},
{
  "description": "CASH BACK",
  "amount": "12.00",
  "type": "1",
  "date": "05/03/2016"
}
]

Now they have changes the API and data is coming like this:

{
  "error": false,
  "wallet": [
    {
      "description": "Cashback",
      "amount": "20.00",
      "type": "1",
      "date": "11/03/2016"
    },
    {
      "description": "CASH BACK",
      "amount": "12.00",
      "type": "1",
      "date": "05/03/2016"
    }
  ]
}    

How to handle object in ONResponse and parse wallet information in array?


回答1:


the PoJo has to change. E.g.

public class NewWallet {
    public boolean error;
    public List<Wallet> wallet;
}

and let your interface return NewWallet instead of ArrayList<Wallet>




回答2:


If your all apis changed like this only, then better to use templates.

public class ResponseDS<T> {
    public boolean error;
    public List<T> data;
}

Now you can pass Wallet or any other Object as T for the response with signature. :)



来源:https://stackoverflow.com/questions/35956104/how-to-handle-object-on-onresponse-of-retrofit-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!