4

I have the following Program which gives me the following error:

System.TypeException: Invalid conversion from runtime type Map<String,ANY> to Map<String,String>

The program which I created is for reference:

String response = '{"access_token":"00D7F0000001I8v!ARgAQMUxsUNMleUjdSk8yn1YsyR1gJ4R8S24BQCfHTIBLpkFiJfEeXxKJARviUBRSAhCM84x96yTXVUXeZWbrlSoVnD729MG","instance_url":"https://ap5.salesforce.com","id":"https://login.salesforce.com/id/00D7F0000001I8vUAE/0057F000000l2bgQAA","token_type":"Bearer","issued_at":"1494093385165","signature":"VsM4LBk6pwK98r8JlxFDsRWKgOKscnQ4h5gwwqDN/Ns="}';
Map<String, String> resMap = (Map<String, String>) JSON.deserializeUntyped(response);

String accessToken = resMap.get('access_token');
System.debug('Access Token : '+accessToken);
1
  • You either need to perform a typed serialization or map to an object not a string.
    – zgc7009
    Commented May 7, 2017 at 14:12

2 Answers 2

6

Just deserialize it as a Map<String, Object>:

String response = '{"access_token":"...","other_properties":"..."}';
Map<String, Object> resMap = (Map<String, Object>)JSON.deserializeUntyped(response);

String accessToken = (String)resMap.get('access_token');
System.debug('Access Token : '+accessToken);
0

As per salesforce doc : https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_class_System_Json.htm. The following method always returns Map<String, Object> hence code should be like below:

String response = '{"access_token":"00D7F0000001I8v!ARgAQMUxsUNMleUjdSk8yn1YsyR1gJ4R8S24BQCfHTIBLpkFiJfEeXxKJARviUBRSAhCM84x96yTXVUXeZWbrlSoVnD729MG","instance_url":"https://ap5.salesforce.com","id":"https://login.salesforce.com/id/00D7F0000001I8vUAE/0057F000000l2bgQAA","token_type":"Bearer","issued_at":"1494093385165","signature":"VsM4LBk6pwK98r8JlxFDsRWKgOKscnQ4h5gwwqDN/Ns="}';
Map<String, Object> resMap = (Map<String, Object>) JSON.deserializeUntyped(response);

Object accessToken = resMap.get('access_token');
System.debug('Access Token : '+accessToken);

Object instanceUrl = resMap.get('instance_url');
System.debug('instanceUrl : '+instanceUrl);

Object MyId = resMap.get('id');
System.debug('id : '+MyId);

Object token_type = resMap.get('token_type');
System.debug('token_type : '+token_type);

Object issued_at = resMap.get('issued_at');
System.debug('issued_at : '+issued_at);

Object signature = resMap.get('signature');
System.debug('signature : '+signature);
1
  • 1
    It returns Object, actually, which may be String, Decimal, Map<String, Object>, List<Object>, Boolean, null, and probably a few other data types as well. You're right that it returns Map<String, Object> in this instance, but it is not always true.
    – sfdcfox
    Commented May 6, 2017 at 20:10

You must log in to answer this question.

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