Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a null value from NSDictionary

I have a JSON Feed:

{
    "count1" = 2;
    "count2" = 2;
    idval = 40;
    level = "<null>";
    "logo_url" = "/assets/logos/default_logo_medium.png";
    name = "Golf Club";
    "role_in_club" = Admin;
}

The problem is the "<null>". I cannot figure out how to remove it from the NSDictionary before saving it to NSUserDefaults.

like image 891
jimbob Avatar asked Jan 03 '13 22:01

jimbob


2 Answers

Another variation, without (explicit) loop:

NSMutableDictionary *dict = [yourDictionary mutableCopy];
NSArray *keysForNullValues = [dict allKeysForObject:[NSNull null]];
[dict removeObjectsForKeys:keysForNullValues];
like image 153
Martin R Avatar answered Oct 02 '22 10:10

Martin R


Iterate through the dictionary and look for any null entries and remove them.

NSMutableDictionary *prunedDictionary = [NSMutableDictionary dictionary];
for (NSString * key in [yourDictionary allKeys])
{
    if (![[yourDictionary objectForKey:key] isKindOfClass:[NSNull class]])
        [prunedDictionary setObject:[yourDictionary objectForKey:key] forKey:key];
}

After that, prunedDictionary should have all non-null items in the original dictionary.

like image 30
Simon Goldeen Avatar answered Oct 02 '22 09:10

Simon Goldeen