9

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

Vicky Thakor
  • 3,847
  • 7
  • 42
  • 67
Vamsi
  • 619
  • 3
  • 9
  • 22
  • 2
    Which line is throwing the exception? The first one? Have you tried replacing `new TypeReference>(){}` with `new TypeReference>>(){}`? – Boris Pavlović Feb 23 '16 at 07:12
  • @BorisPavlović, Yes I tried it now and I am getting exception telling: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token at [Source: {"total":1,"movies":[{"id":"771390242","title":"Deadpool"}] – Vamsi Feb 23 '16 at 07:18
  • Use `Map obj = mapper.readValue(result.getBody(), new TypeReference>(){});` –  Feb 23 '16 at 07:32
  • were you able to resolve this? – tranquil Mar 16 '17 at 05:27

2 Answers2

2

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());
}
Lilia
  • 462
  • 6
  • 22
1

Try This : Are you trying to Store MapObject in List.so instead of Map store in List.

instead of:

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

Use This :

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

For Demo example This Link

Benjamin
  • 2,257
  • 1
  • 15
  • 24
  • Hey @Benjamin, I tried it. After trying that I got this error: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token at [Source: {"total":1,"movies":[{"id":"771390242","title":"Deadpool"}] – Vamsi Feb 23 '16 at 07:27