I have an APEX callout that makes a call to a REST API and returns an object, in this case I am calling /services/data/v48.0/sobjects/Case/describe
. I was trying to use this same APEX class to call out to another 3rd party endpoint, however, that endpoint is returning a list
.
This causes an error of FATAL_ERROR System.TypeException: Invalid conversion from runtime type List<ANY> to Map<String,ANY>
.
Is there a way I can adapt this callout to be able to handle both situations? I'm not really going to know what the response type will always be.
Code:
public static map<String, Object> GetCallout(string namedCredential, string endpoint) {
HTTPRestService_EnterpriseCaseCreation caseService = new HTTPRestService_EnterpriseCaseCreation();
HttpResponse calloutResponse = caseService.makeGetCallout(namedCredential, endpoint);
map<String, Object> mapJsonData = new map<String, Object>();
String strResponse = null;
try {
if (calloutResponse.getStatusCode() == 200) {
strResponse = calloutResponse.getBody();
} else {
throw new CalloutException(calloutResponse.getBody() );
}
} catch (Exception ex) {
throw ex;
}
if (!String.isBlank(strResponse) ) {
mapJsonData = (map<String, Object>) JSON.deserializeUntyped(strResponse);
}
if (!mapJsonData.isEmpty() ) {
return mapJsonData;
} else {
return null;
}
}
map<String, Object> test = GetCallout('SF_Enterprise', '/services/data/v48.0/sobjects/Case/describe');
map<String, Object> test2 = GetCallout('Mule_ESB_Crosswalk_Service', '?guid=9C7E57CF-2DC7-4C89-B476-11166DED34DC'); // Invalid conversion from runtime type List<ANY> to Map<String,ANY>
System.debug(test); // Line 46
System.debug(test2); // Line 47
The image shows what the responses look like before I try to use map
and just see the response as a string.
Is there a more dynamic way to handle these various scenarios?