5

Given a JSON response from a remote API call, I can use JSON.DeserializeUntyped to get an Object, which can then be cast to another type as needed. For example:

String jsonResponse = makeAPICall(); //defined elsewhere
Object objResponse = JSON.DeserializedUntyped(jsonResponse);

// if I expect a list of something:
list<Object> responseList = (list<Object>)objResponse;

// but if I expect a map:
map<string, Object> responseMap = (map<string, Object>)objResponse;

Is there any way of determining anything about Object? I can't find any documentation on the type. In my particular case, I need to know if the json response contains a list or a map... I don't even need to know what kind of list or map, since there are only two possibilities for the method I'm calling (a list of objects, or a map describing an error). Possibilities I've considered:

  • peek at the beginning of the json string
  • attempt to cast inside a try-catch block

Not a fan of either approach, was hoping for some way of checking the type (expecting, for example, Object, List<Object>, or Map<string, Object>), does such a thing exist? Is this just bad API design?

  • 2
    Yep, you can do (obj instanceof MyClass) etc – bigassforce Jun 23 '14 at 20:22
  • 1
    Wow, I'd forgotten that apex supports the instanceOf operator. Confirmed, e.g., (obj instanceOf list<Object>) works perfectly. Please make that an answer so I can accept it :) – Jason Clark Jun 23 '14 at 20:34
7

You can use the instanceof operator:

if (obj instanceof MyClass) //...
else if (obj instanceof MyObject__c) //...
else if (obj instanceof Map<String,String> //...

I'd reckon there's still a desirable future Apex feature here as there's no reliable way to get the Type from an object instance.

2

Ideally you shouldn't need such checks, and its BAD API design to consume a resource which can return either a MAP or LIST. Anyway, this code snippet shows how to check for both map and list

Object mapObj = JSON.deserializeUntyped ('{"Key1" : "Value1"}');
System.debug('Is Map: ' + (mapObj instanceof Map<String, Object>) );

Object arrObj = JSON.deserializeUntyped ('["Apple", "Orange"]');
System.debug('Is List: ' + (arrObj instanceof List<Object>) );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.