0

I understand I am getting this error on the map line but I do not understand why. As the method does return the list I am constructing. What am I missing about this exactly?

The dataRequest starts as a String Type JSON object.

Incoming JSON sample:

    JSON =[{"crm_id":"0014000001aWzBlAAK","email_addresses":"email1, email2"}]

Code:

     public static List<Contact> addConData() {

    //requests the selected look
    dataRequest = lookerCallout.getData('2');
    dataRequest = dataRequest.replace('crm_id', 'AccountId');
    dataRequest = dataRequest.replace('email_addresses', 'Email');

    //This line returns the error: System.TypeException: Invalid conversion from runtime type List<ANY> to Map<String,ANY>
    Map<String, Object> jsonMap = (Map<String, Object>)JSON.deserializeUntyped(dataRequest);


    List<String> emailParse = ((String)jsonMap.get('Email')).split(',');
    List<Contact> dataRequestList = new List<Contact>();
    String accId = (String)jsonMap.get('AccountId');
    for(String em : emailParse){
        dataRequestList.add(new Contact(AccountId =accId, Email = em.trim()));
    }
    //debug piece for this method
    //System.debug(dataRequestList);
    System.debug(dataRequestList.size());

    return dataRequestList;    
}
2
  • Please edit your post to include the exact message verbatim, and clearly indicate which line throws the error.
    – Adrian Larson
    Aug 16, 2019 at 15:36
  • 1
    and what the incoming json looks like ...
    – cropredy
    Aug 16, 2019 at 15:40

1 Answer 1

5

The structure of your string payload does in fact clearly indicate a List structure, as it starts with a square bracket ([). You have a List<Map<String, Object>>. However, you have to deserialize into List<Object> then cast afterward.

List<Object> data = (List<Object>)JSON.deserializeUntyped(payload);
for (Object datum : data)
{
    Map<String, Object> innerData = (Map<String, Object>)datum;
}

As mentioned in the comments, you also don't need to use the untyped version if you know the structure.

String payload = '[{"crm_id":"0014000001aWzBlAAK","email_addresses":"email1, email2"}]';
List<Map<String, String>> data = (List<Map<String, String>>)JSON.deserialize(
    payload, List<Map<String, String>>.class
);
for (Map<String, String> datum : data)
{
    system.debug(datum);
}
2
  • 1
    Alternatively, since the values (at least in the example) are all strings, why not use typed deserialization? List<Map<String, String>> data = (List<Map<String, String>>) JSON.deserialize(payload, List<Map<String, String>>.class)
    – Phil W
    Aug 16, 2019 at 15:58
  • So the bracket in here ([) is just on the debug log line. I am pretty new to apex, but once you iterate through the map object do I just apply it to the List the same way I was doing?
    – Randy B.
    Aug 16, 2019 at 17:15

You must log in to answer this question.

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