I am trying to parse data that I get from an external webservice with a get api callout.

When running the code I get the error :

Line: 14, Column: 1 System.TypeException: Invalid conversion from runtime type List to Map<String,ANY>

The data I am getting from the callout is looks like this :

12:18:46:383 USER_DEBUG [15]|DEBUG|>>>>>[{"name":"Afghanistan","topLevelDomain":[".af"],"alpha2Code":"AF","alpha3Code":"AFG","callingCodes":["93"],"capital":"Kabul","altSpellings":["AF","Af\u0121\u0101nist\u0101n"],"region":"Asia"},{"name":"\u00c5land Islands","topLevelDomain":[".ax"],"alpha2Code":&q.

My code I am running when parsing looks like this:

    Http http = new Http();
    HttpRequest request = new HttpRequest();
    HttpResponse response = http.send(request);
 Object countries;
   string returnValue;
    // If the request is successful, parse the JSON response
    if (response.getStatusCode() == 200) {
        // Deserialize the JSON string into collections of primitive data types.
        Map<string, Object> result = (Map<string, Object>) JSON.deserializeUntyped(response.getBody());
        countries = result.get('listCountries');

Can you please help me understand what am I doing wrong ?


2 Answers 2


Let's break down your error a little bit:

  • Your JSON starts (and presumably ends) with []. That makes it a list (a JSON array)
  • You're trying to deserialize to a (Map<string, Object>)

Thus you get your error, you have a List<Object>, and you're trying to cast it as a Map<String, Object>. Those two types are not compatible, so you get an error.

As a first step...

Map<string, Object> result = (Map<string, Object>) JSON.deserializeUntyped(response.getBody());

needs to be

List<Object> result = (List<Object>) JSON.deserializeUntyped(response.getBody());

Your JSON is a list, so you need to deserialize to a list.

Your JSON doesn't contain anything called listCountries, so result.get('listContries'); is also wrong. JSON doesn't give you any special methods or access to the data, it only contains the data.

To extract information from your JSON, you'll need to loop over the List<Object> (and do more typecasting, deserializing untyped ends up needing a lot of typecasting) to get at specific fields.

  • thank you, i sort of worked. thanks for the help
    – Alpar.Balo
    Jul 17, 2022 at 22:40

Since in your case, the return is an array deserialize to a List<Object> like below

    List<Object> results = (List<Object>) JSON.deserializeUntyped(response.getBody());

And now you can loop over each object and deserialize to a Map<String, Object> as shown below

for(Object result: results) {
    Map<String, Object> data = (Map<String, Object>)result;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .