DevC
DevC

Reputation: 7022

Parsing JSON and checking whether key exists

Im parsing JSON from a server, however I have the problem that if the user does not have a credit card attached to an account it returns this:

enter image description here

But when they do have a credit card attached it returns this:

enter image description here

Ive tried the following code to determine whether card_first_name is not nil, but it crashes because obviously card_first_name does not exist yet. How would I handle this situation? Please see my current code below:

if (dict[@"message"][@"card_details"] !=[NSNull null]) {
    if (dict[@"message"][@"card_details"][@"card_first_name"]!=nil)       /*crashes here */ {
        NSLog(@"%@",dict[@"message"][@"card_details"][@"card_first_name"]);

    }
    if (dict[@"message"][@"card_details"][@"card_last_name"]!=[NSNull null]) {
        NSLog(@"%@",dict[@"message"][@"card_details"][@"card_last_name"]);

    }
    if (dict[@"message"][@"card_details"][@"card_number"]!=[NSNull null]) {
        NSLog(@"%@",dict[@"message"][@"card_details"][@"card_number"]);

    }

    if (dict[@"message"][@"card_details"][@"card_type"]!=[NSNull null]) {
        NSLog(@"%@",dict[@"message"][@"card_details"][@"card_type"]);

    }
    if (dict[@"message"][@"card_details"][@"expiry"]!=[NSNull null]) {
        NSLog(@"%@",dict[@"message"][@"card_details"][@"expiry"]);

    }
    if (dict[@"message"][@"card_details"][@"payment_ref"]!=[NSNull null]) {
        NSLog(@"%@",dict[@"message"][@"card_details"][@"payment_ref"]);


    }
}

Thanks in advance, and any help is greatly appreciated.

Upvotes: 0

Views: 67

Answers (2)

RLS
RLS

Reputation: 311

Determine if there is a key count for card details.

NSUInteger keyCount = [dictionary count];

Upvotes: 1

ares777
ares777

Reputation: 3628

Just verify first if key exists then check if has value:

       if(dict["message"]key key) 

do this starting from the first possible (expected) key, in your case "message", then for all subseqwent (expected keys, subkeys).

Upvotes: 0

Related Questions