[SalesForce] Invalid conversion from runtime type LIST to MAP

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!

Best Answer

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);
Related Topic