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
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();
}
});
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", "");
}
}
};
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.