0

I am passing the response of an API call (Retrofit used) to a class and trying to cast it to my model class. Since i am using retrofit for the API call, it generates a linked hashmap based on the response from the server prior to convert it into model class object using Gson. (That is what i understand, correct me if i am wrong). I have attached an image of what i can see when i debug with the response object. How can i convert this response into an object of my model class or type Object. I am getting class cast exception when i attempt to cast type Object into my model class inside my activity.

Here is my code

API Call

call.enqueue(new Callback() {

        @Override
        public void onResponse(Call call, Response response) {
            if (response.body() != null) {   
                        List<CategoriesBaseModel> categoryBaseResponseList = (List<CategoriesBaseModel>) response.body();
                        List<Object> categoryResponseList = (List<Object>) categoryBaseResponseList.get(0).getData();
                        if (categoryResponseList != null) {
                           mCategoriesInterface.passCategoriesResponse(categoryResponseList, "HomeFragment");
                        }
            }                
        }
        @Override
        public void onFailure(Call call, Throwable t) {

            call.cancel();
        }
    });

Activity

CategoriesInterface categoriesInterface = new CategoriesInterface() {
    @Override
    public void passCategoriesResponse(List<Object> scheduleList, String name) {
        CategoriesModel categoriesModel;
        for (Object model : scheduleList){
            categoriesModel = (CategoriesModel) model;
            Log.d("TAG", "");
        }
    }
};

enter image description here

1 Answers1

0

Solved this by converting the Object into Json string and coverting it back directly to the model class object.

Gson gs = new Gson();
String js = gs.toJson(model);
categoriesModel = gs.fromJson(js, CategoriesModel.class);
  • Whilst the code is compact, this is not a very performant option. You serialize and then deserialize. It might not make much difference, if you do not have much data, but if you do, this is quite bad for performance. – gil.fernandes Jan 11 '18 at 10:53