0

I am getting below Response from the API

{
"APIResponse": {
    "APIResult": []
}}

I have done a null check like below and storing the result in Map

if(Response != null && Response.containsKey('APIResult') && Response.get('APIResult') != null && Response.get('APIResult') != ''){
   Result = (map<string, object>)Response.get('APIResult'); 

But this is giving me the error

common.apex.runtime.impl.ExecutionException: Invalid conversion from runtime type List to Map

How can I do a null check here?

Thanks

1

Looking at your response code APIResult is type of Array all you can do is if Array size > 0 consider that list is not empty or you can use List.isEmpty() method to check your APIResult as got any values.

Here is the example code

String response = '{ "APIResponse": { "APIResult": [] } }';
Map<String, Object> responseMap = (Map<String, Object>)JSON.deserializeUntyped(response);

List<object> apiResponse = (List<Object>)responseMap.get('APIResult');
if(apiResponse!=null){
    // Process your logic
}
| improve this answer | |
1

APIResult is of type list and not a key value pair map. So convert it into list.

 list< object> Result = (list< object>)Response.get('APIResult'); 

and then you can check size of this list

if(Result.size() > 0) {

}

You can alsu use apex class to easily parse this JSON

public class fromJSON{
    public cls_APIResponse APIResponse;
    class cls_APIResponse {
        public cls_APIResult[] APIResult;
    }
    class cls_APIResult {
    }
    public static fromJSON parse(String json){
        return (fromJSON) System.JSON.deserialize(json, fromJSON.class);
    }

    static testMethod void testParse() {
        String json=        '{'+
        '"APIResponse": {'+
        '    "APIResult": []'+
        '}}';
        fromJSON obj = parse(json);
        System.assert(obj != null);
    }
}
| improve this answer | |

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.