Invalid conversion from runtime type LIST<ANY> to MAP<String,ANY>

  • I'm trying to make a webcall to pull data from an external webservice. After that call I would like to insert my data that comes in the form of JSON into my custom object called Company. However I am getting the following error: System.TypeException: Invalid conversion from runtime type LIST to MAP

    Here is how the JSON would come in:

    {"Id":"JOE1","Name":"Joes Software"}, {"Id":"REX1","Name":"Rex Software"} etc...

    My class:

    public with sharing class Callout {
    
    public static void performAction(String method, String webCall){
    
                Blob headerValue = Blob.valueOf('username:password');  
                String endPoint = 'https://www.mockwebsite.com/WebAPI/api/';
                String jsonData;
    
                HttpRequest req = new HttpRequest();
    
                String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
                endPoint = endPoint + webCall;  
                req.setEndpoint(endPoint);
                req.setMethod(method);
                req.setHeader('Authorization', authorizationHeader);
                req.setHeader('Content-Type', 'application/json');
    
                Http http = new Http();
                HTTPResponse res = http.send(req);
    
    
                Map<String, Object> data = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());  
    
                List<Object> items = (List<Object>)data.get('Items');
                List<Company__c> new_items = new List<Company__c>();
                for(Object item : items) {
                Map<String, Object> item_data = (Map<String, Object>)item;
                Company__c cpny = new Company__c();
                cpny.Name = (String)item_data.get('Name');
                cpny.Company_ID__c = (String)item_data.get('Id');
                new_items.add(cpny);
                }
    
      }
    }
    

    It doesn't like line

    Map<String, Object> data = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
    

    Any ideas? Thanks!

    What is the line number where the error message indicates that there's a problem?

    if you could give how the JSON response looks like we can help you debug and fix this simple issue

    The response looks like this: [{"Id":"OS","Name":"Orion Software"},{"Id":"CS","Name":"Constellation Software"}]

  • If the response type is known and this is going to be an ongoing process, would creating a response class for that make sense?

    public class MockResponse{
      public String Id;
      public String Name;
    }
    ...
    List<MockResponse> responseList = (List<MockResponse>)JSON.deserialize(res.getBody(), MockResponse.class);
    

    This wasn't working for me exactly. I used the following syntax: `List responseList = (List)JSON.deserialize(res.getBody(), List.class);`

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM