NutzCN Logo
问答 关于Json.toJosn 泛型问题请教
发布于 1079天前 作者 Saviour 1154 次浏览 复制 上一个帖子 下一个帖子
标签:

大佬请问一个问题,我有调用远程接口需求,将每个接口的返回封装成对象,统一写调用,代码片段如下:

public static <T> BaseResult<T> doQuery(BaseQuery query) throws Exception {
    Request request = Request.create(query.url(), Request.METHOD.POST);
    .....
    Response resp = Sender.create(request).send();
    String content = resp.getContent();
    return Json.fromJson(new PType<BaseResult<T>>(){}, content);
}

使用代码片段:

   BaseQuery<PagerData<School>> query = new SchoolPagerQuery<>()
   BaseResult<PagerData<School>> result = Querier.doQuery(query);
    if(result != null) {
                PagerData<School> pagerData = result.getData();//此行报错
                List<School> schoolList = pagerData.getItems();
                for (School school : schoolList) {
                    System.out.println(school);
                }
     }

其中BaseResult中泛型用的层次较多,代码如下:

public static <T> BaseResult<T> doQuery(BaseQuery query) throws Exception {
    Request request = Request.create(query.url(), Request.METHOD.POST);
    .....
    Response resp = Sender.create(request).send();
    String content = resp.getContent();
    return Json.fromJson(new PType<BaseResult<T>>(){}, content);
}
  public class BaseResult<T> {
    .... 其他非泛型属性
    /**
     * 返回结果
     */
    private T data;
}

public class PagerData<E> {
    private Integer total;
    private Integer currentPage;
    private Integer perPage;
    private List<E> items;
}

public class School {
     ....其他常规属性
    private SchoolAuth schoolAuth;
    private SchoolExt schoolExt;
}

此代码运行后,返回的都是java.util.LinkedHashMap
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.limit.kindergarten.common.remote.dto.result.PagerData
想请教大佬,是否能实现自动装配泛型到正确的对象,如果可以应该如何写,衷心谢谢大佬

1 回复

大概有点思路了,模仿Json.toJson(Class clazz, ..)试一试,把真实想要的类型传过去
doQuery(Class clazz, BaseQuery query)

添加回复
请先登陆
回到顶部