优秀的编程知识分享平台

网站首页 > 技术文章 正文

jackon 封装 自定义 泛型 导致 ClassCastException

nanyue 2024-08-26 18:03:23 技术文章 6 ℃

写法问题,以下是原代码

public <T> List<T> parseListFromJson(String rawStr,Class<T> clazz) {

List<T> list = null;

try {

list = JsonUtils.getObjectMapperInstance().readValue(rawStr, new TypeReference<List<T>>() {});

} catch (IOException e) {

logger.error("反序列化属性失败,{}", e.getMessage());

}

return list;

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

这样写是没用的,自定义的T是不能被识别的,但是把换成具体的类名,又可以运行。。。这个表示有点坑爹

以下是正确的写法

public <T> List<T> parseListFromJson(String rawStr,Class<T> clazz) {

List<T> list = null;

try {

JavaType userType = TypeFactory.defaultInstance().constructCollectionType(List.class,clazz);

list = JsonUtils.getObjectMapperInstance().readValue(rawStr, userType);

} catch (IOException e) {

logger.error("反序列化失败,{}", e.getMessage());

}

return list;

}

Tags:

最近发表
标签列表