user12019098
user12019098

Reputation:

Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast t

I am trying to consume rest service using retrofit2 and it works fine when my pojo does not have a generic type. When I don't use generic everything works fine. Here is my retrofit Service. The error is occurring at the point of iterating over the Array List as shown in the picture in the This Link.

   public interface EposService 
{
    @POST("v1/api/product/load_product")
    public Call<RestResponseObject> getProducts(@Body ProductParam udata);    

}
public class RestResponseObject<T> {
       public String message;
        private Object payload;
        private boolean responseStatus,status;
        List<T> data;//getter setter
}
public class ProductBean  {

     private String make, manufacture_year, name;//getter setter

}
private static RestResponseObject<ProductBean> findProducts(ProductParam pay) {
         RestResponseObject mv=new RestResponseObject();
          EposService service = retrofit.create(EposService.class);

        final Call<RestResponseObject> call = service.getProducts(pay);

        try {
            Response<RestResponseObject> resp = call.execute();
           if(resp!=null)
                {
            if (resp.code() == 200) {


                       mv=resp.body();

            } 
            else{

               // mv.setStatus(false);//("05");
                //mv.setMessage("connection error");
            }
        }

        } catch (Exception e) {

          e.printStackTrace();

        }

        return mv;
    }

Here is full stack trace.

Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to api.bean.ProductBean
    at retrofit.Exec.main(Exec.java:63)

Upvotes: 0

Views: 1149

Answers (1)

Peter
Peter

Reputation: 648

The object being received is being converted into a LinkedTreeMap by your JSON converter, and you shall somehow need to convert it into a ProductBean for you to access it

Comment out the for loop you have and paste the below code below it and see what happens:

for(Object b: ps)
{
    ProductBean bean = new Gson().fromJson(new Gson().toJson(((LinkedTreeMap<String, Object>) b)), ProductBean.class);
    System.out.println(bean.getName());
}

(Based on this answer)

Upvotes: 2

Related Questions