Exception java.util.LinkedHashMap cannot be cast to java.util.List

Vamsi picture Vamsi · Feb 23, 2016 · Viewed 36.3k times · Source

While working around following code I got the exception given below.

List<Map<String, Object>> obj = mapper.readValue(result.getBody(), new TypeReference<Map<String,Object>>(){});

for (Map<String, Object> map : obj) {
    for(Map.Entry<String, Object> entry : map.entrySet()){
        System.out.println("Key : "+entry.getKey()+" Value is: "+entry.getValue());
    }
}

Stacktrace: java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to java.util.List

Answer

Lilia picture Lilia · Apr 24, 2017

You need to use only a Map instead of List of Map.

 Map<String, Object> object = mapper.readValue(result.getBody(), new TypeReference<Map<String,Object>>(){});
 for(Map.Entry<String, Object> entry : object.entrySet()){
    System.out.println("Key : "+entry.getKey()+" Value is:"+entry.getValue());
}