首页 > 代码库 > Jackson转换泛型List出现错误java.util.LinkedHashMap cannot be cast to com.xxx

Jackson转换泛型List出现错误java.util.LinkedHashMap cannot be cast to com.xxx

使用stackoverflow上的代码描述这个问题:

  ObjectMapper mapper = new ObjectMapper();

    List<ConsultantDto> list = new ArrayList<ConsultantDto>();


    try {

        list = mapper.readValue(con.getInputStream(), ArrayList.class);

    } catch (JsonGenerationException e) {

        e.printStackTrace();

    } catch (JsonMappingException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

转换不会出现错误,但是获取具体数据时会抛出异常:

System.out.println(list.get(0));
System.out.println(list.get(0).getForename());
return list;

<span style="color:#FF0000;"><strong>java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.xxx.xxx.web.dto.rp.ConsultantDto</strong></span>
异常信息很少。

解决办法:

List<ConsultantDto> myObjects =
    mapper.readValue(jsonInput, new TypeReference<List<ConsultantDto>>(){});

Jackson转换泛型List出现错误java.util.LinkedHashMap cannot be cast to com.xxx