user1285402
user1285402

Reputation: 163

How to check if NSDictionary is null and read the JSON value in objective c

I want to check if NSDictionary is NULL or not and read the JSON values.

Here is my code for checking if NSDictionary is null :

if ([dataDict objectForKey:@"messages"]!= NULL) {
     NSLog(@"not null");
}
else
{
NSLog(@"null");
}

When I print the value for [dataDict objectForKey:@"messages"] it's: messages = "<null>"

I want to read the JSON value "message": "Not valid." if messages is not null :

"messages": {
      "items": [
        {
          "message": "Not valid."
        }
      ]
    }

Upvotes: 0

Views: 78

Answers (1)

rmaddy
rmaddy

Reputation: 318814

If you see the output "<null>" then this means the value is an instance of NSNull. So you need to check for that as well.

I would update your code as follows:

id message = dataDict[@"messages"];
if (message == nil || message == [NSNull null]) {
    NSLog("null");
} else {
    NSLog("not null");
    if ([message isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dict = (NSDictionary *)message;
        NSArray *items = dict[@"items"];
        if (items.count > 0) {
            NSString *message = items[0][@"message"];
            NSLog(@"Message: %@", message);
        }
    }
}

Upvotes: 1

Related Questions