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

4
  • 2
    Which line is throwing the exception? The first one? Have you tried replacing new TypeReference<Map<String,Object>>(){} with new TypeReference<List<Map<String,Object>>>(){}? Commented Feb 23, 2016 at 7: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"}] Commented Feb 23, 2016 at 7:18
  • Use Map<String, Object> obj = mapper.readValue(result.getBody(), new TypeReference<Map<String,Object>>(){}); Commented Feb 23, 2016 at 7:32
  • were you able to resolve this? Commented Mar 16, 2017 at 5:27

2 Answers 2

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());
}
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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"}]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.