繁体   English   中英

java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap 无法转换为模型类 android

[英]java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to model class android

我正在将API调用(使用Retrofit )的响应传递给一个类,并尝试将其转换为我的模型类。 由于我正在对API调用进行改造,因此在使用Gson将其转换为模型类对象之前,它会根据来自服务器的响应生成一个链接的哈希图。 (这就是我的理解,如果我错了,请纠正我)。 我附上了一张我在调试响应对象时可以看到的图像。 我如何将此响应转换为我的模型类或类型 Object. 当我尝试将类型 Object 转换为我的活动中的模型类时,出现类转换异常。

这是我的代码

API调用

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", "");
        }
    }
};

在此处输入图片说明

通过将 Object 转换为 Json 字符串并将其直接转换回模型类对象来解决此问题。

Gson gs = new Gson();
String js = gs.toJson(model);
categoriesModel = gs.fromJson(js, CategoriesModel.class);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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