JSON.DeserializeUntyped: Can I infer anything from the Object returned?

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?

Answer

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.

Attribution
Source : Link , Question Author : Jason Clark , Answer Author : Matt and Neil

Leave a Comment