-1

System.TypeException: Invalid conversion from runtime type List to Map, can anyone suggest what should be the type???

public with sharing class blocxHeroController{
public map<String, Object> getHeroDetails(String strEndPointURL){

map<String, Object> mapJsonData = new map<String, Object>();
String strResponse = null;
if(String.isNotBlank(strEndPointURL)) {
HttpRequest httpRequest = new HttpRequest();  
httpRequest.setEndpoint('https://api.myjson.com/bins/xfx0i');
httpRequest.setMethod('GET');   
try {  
    Http http = new Http();   
    HttpResponse httpResponse = http.send(httpRequest);  

    while(httpResponse.getStatusCode() == 302) {
        // httpRequest.setEndpoint(httpResponse.getHeader('Location'));
        httpResponse = new Http().send(httpRequest);
    }
    if (httpResponse.getStatusCode() == 200 ) {  
        strResponse = httpResponse.getBody();  
    } 
    else {  
        throw new CalloutException(httpResponse.getBody());  
    }   
} 
catch(Exception ex) {  
    throw ex;  
}  
} 
if(!String.isBlank(strResponse)) {
mapJsonData = (map<String, Object>)JSON.deserializeUntyped(strResponse);
System.debug('mapJsonData ===> '+ mapJsonData);
}
if(!mapJsonData.isEmpty()) {
return mapJsonData;
}
else {
return null;
}
}
}
  • In which line you have error ? – Rijwandeltax Feb 10 at 12:25
  • 1
    api.myjson.com/bins/xfx0i returns an array objects, while map<String, Object>)JSON.deserializeUntyped(strResponse); tries to cast that to a Map<String, Object> – kurunve Feb 10 at 12:32
  • @kurunve An answer would have been more appropriate than a comment. – sfdcfox Feb 10 at 13:39
0

As defined in the endpoint (https://api.myjson.com/bins/xfx0i), returned data does look like following:

[
    {
        "altText": "sample",
        "description": "sample",
        "header": "sample",
        "href": "#",
        "id": 1,
    },
    {
        "altText": "Second card accessible description.",
        "description": "Third Slide description",
        "header": "Third Slide",
        "href": "#",
        "id": 2,
        "image": "sample"
    }
]

In order to process it properly, it is necessary to cast that to an array of objects first:

List<Object> json_array_data;
if(!String.isBlank(strResponse)) {
    json_array_data = (List<Object>)JSON.deserializeUntyped(strResponse);
    System.debug('json_array_data ===> '+ json_array_data);
}

After that, each entry of the array can be casted to Map<String, Object> and processed one by one.

| improve this answer | |
  • i'm not clear can you brief me please???@kurunve – user78808 Feb 11 at 6:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.