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
How to handle ClassCastException. To prevent the ClassCastException exception, one should be careful when casting objects to a specific class or interface and ensure that the target type is a child of the source type, and that the actual object is an instance of that type.
The LinkedHashMap class of the Java collections framework provides the hash table and linked list implementation of the Map interface. The LinkedHashMap interface extends the HashMap class to store its entries in a hash table. It internally maintains a doubly-linked list among all of its entries to order its entries.
You can convert all the keys of LinkedHashMap to a set using Keyset method and then convert the set to an array by using toArray method now using array index access the key and get the value from LinkedHashMap.
The Major Difference between the HashMap and LinkedHashMap is the ordering of the elements. The LinkedHashMap provides a way to order and trace the elements. Comparatively, the HashMap does not support the ordering of the elements.
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());
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With