线程 "main" java.lang.ClassCastException 中的异常:com.google.gson.internal.LinkedTreeMap 无法转换为 t

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

我正在尝试使用 retrofit2 使用休息服务,当我的 pojo 没有通用类型时它工作正常。当我不使用通用时,一切正常。这是我的改装服务。错误发生在遍历数组列表时,如 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;
    }

这是完整的堆栈跟踪。

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)

您的 JSON 转换器正在将接收到的对象转换为 LinkedTreeMap,您将需要以某种方式将其转换为 ProductBean 以便您访问它

注释掉您的 for 循环并将下面的代码粘贴到它下面,看看会发生什么:

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

(基于 this 回答)