简体   繁体   中英

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)

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)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM