0

The Json file is:

{
  "data": [
    {
      "name": "key",
      "error": "key is not valid"
    },
    {
      "name": "package_name",
      "error": "package name is not valid"
    }
  ],
  "success": false,
  "message": "information is not valid"
}

I've got a BaseModel which has "success","message", "data" and all of my responds are extended from this Class. But "data is different for each response from the server.

I've made this so far:

public class BaseModel{
    private Object data;
    private boolean success;
    private String message;
}

which data for this case of error will cast to an array of DataError:

public class DataError{
        private String name;
        private String error;
}

And i get an error which tells me :

java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com.example.mapp.Model.DataError

List<DataError> dataError = (List<DataError>)response.body().getData();
textView.append("Error:"+ dataError.get(0).getError());
Behnawwm
  • 121
  • 2
  • 9

1 Answers1

0

You need to have a List<DataError> when parsing, Although it can also parse as a Map. Create data in BaseModel Generic this way you can reuse it other classes as well. naming it to BaseListModel cause it return a list.

public class BaseListModel<T>{
private List<T> data;
private boolean success;
private String message;
}

Now you can make the API call return BaseListModel<DataError> .

For parsing Object type responses you can create other base class .

 public class BaseModel<T>{
 private T data;
 private boolean success;
 private String message;
}
ADM
  • 20,406
  • 11
  • 52
  • 83
  • The problem is all "data" in other responses are not always a list ! – Behnawwm Sep 12 '20 at 11:58
  • That is why you create a other base class which will have `data` as Object . I updated the answer . Pls check – ADM Sep 12 '20 at 11:59
  • by this way, can i check if the "success" is true, i get a "BaseModel" and if it's false, the "BaseListModel" ? – Behnawwm Sep 12 '20 at 13:47
  • Response structure should be same whether its an error or success . In case of Error data Should be a blank Array `"data":[ ]` not an object it will violate the Contract and throw a parsing error.. Otherwise you have to do something [Like this](https://stackoverflow.com/questions/24279245/how-to-handle-dynamic-json-in-retrofit) which is tedious IMO . – ADM Sep 12 '20 at 13:52