Developer
Developer

Reputation: 832

Check and replace all null values with empty string in NSDictionary/NSArray

I am storing my json response in a NSDictionary and this dictionary contains various array, so I want to replace all the null values with @"" empty string.

{
    Specialities =     (
                {
            ApprovalStatus = Unapproved;
            CurrencyCode = "<null>";
            Packages =             (
                                {
                    AssetId = 157965;
                    BasePrice = 10000;
                    BookingAdvance = 100;
                    Currency = INR;
                    Details = "<null>";
                    DiscountedPrice = 9000;
                    Id = 16579;
                    IsBestOffer = 1;
                    IsPopular = 1;
                    LineItems =                     (
                                                {
                            IconClass = "fa-check";
                            Text = "A DVD with all edited and unedited images";
                        }
                    );
                    PackageVersion = 123955;
                    PriceUnit = 3;
                    Quantity = 4;
                    SpecialityId = 22;
                    Status = Rejected;
                    Tags =                     (
                        53
                    );
                    TermsAndConditions = "<null>";
                    Title = Test;
                }
            );
            Photos =             (
                157965,
                157964
            );
            ServiceDescription = 43534;
            Speciality = 22;
            SpecialityName = "Wedding Photographer";
            UserFRPs =             (
                                {
                    AssetId = 157965;
                    CurrencyCode = INR;
                    DiscountedPrice = 800;
                    FRPId = 13;
                    Id = 4559;
                    Price = 1000;
                    SpecialityId = 22;
                    Status = Active;
                },
                                {
                    AssetId = 565441;
                    CurrencyCode = INR;
                    DiscountedPrice = 9000;
                    FRPId = 18;
                    Id = 5559;
                    Price = 10000;
                    SpecialityId = 22;
                    Status = Active;
                }
            );
            Videos =             (
                                {
                    VideoId = DaWOguXZbNA;
                    VideoLink = "http://www.youtube.com/watch?v=DaWOguXZbNA";
                    VideoType = YouTube;
                },
                                {
                    VideoId = DGVJtAHzzDQ;
                    VideoLink = "http://www.youtube.com/watch?v=DGVJtAHzzDQ";
                    VideoType = YouTube;
                },
                                {
                    VideoId = "_zxKLZR-xuk";
                    VideoLink = "http://www.youtube.com/watch?v=_zxKLZR-xuk";
                    VideoType = YouTube;
                },
                                {
                    VideoId = 5SkBZcvuuQs;
                    VideoLink = "http://www.youtube.com/watch?v=5SkBZcvuuQs";
                    VideoType = YouTube;
                },
                                {
                    VideoId = "H_Xi-lVB4Zw";
                    VideoLink = "http://www.youtube.com/watch?v=H_Xi-lVB4Zw";
                    VideoType = YouTube;
                },
                                {
                    VideoId = TWhSjpsGvPQ;
                    VideoLink = "http://www.youtube.com/watch?v=TWhSjpsGvPQ";
                    VideoType = YouTube;
                },
                                {
                    VideoId = N2CJrhHEydA;
                    VideoLink = "http://www.youtube.com/watch?v=N2CJrhHEydA";
                    VideoType = YouTube;
                },
                                {
                    VideoId = Lq6faQVYcwY;
                    VideoLink = "http://www.youtube.com/watch?v=Lq6faQVYcwY";
                    VideoType = YouTube;
                },
                                {
                    VideoId = v8WjMiodcKo;
                    VideoLink = "http://www.youtube.com/watch?v=v8WjMiodcKo";
                    VideoType = YouTube;
                }
            );
        },
                {
            ApprovalStatus = Unapproved;
            CurrencyCode = "<null>";
            Packages = "<null>";
            Photos =             (
                157967
            );
            ServiceDescription = Ddhd;
            Speciality = 37;
            SpecialityName = "Hair and Makeup Stylist";
            UserFRPs =             (
                                {
                    AssetId = 157967;
                    CurrencyCode = INR;
                    DiscountedPrice = 900;
                    FRPId = 34;
                    Id = 4560;
                    Price = 1000;
                    SpecialityId = 37;
                    Status = Active;
                }
            );
            Videos =             (
                                {
                    VideoId = "onvkllwM-OI";
                    VideoLink = "http://www.youtube.com/watch?v=onvkllwM-OI";
                    VideoType = YouTube;
                },
                                {
                    VideoId = "_-cRVdTW2s8";
                    VideoLink = "http://www.youtube.com/watch?v=_-cRVdTW2s8";
                    VideoType = YouTube;
                },
                                {
                    VideoId = DGVJtAHzzDQ;
                    VideoLink = "http://www.youtube.com/watch?v=DGVJtAHzzDQ";
                    VideoType = YouTube;
                }
            );
        },
                {
            ApprovalStatus = Unapproved;
            CurrencyCode = "<null>";
            Packages = "<null>";
            Photos =             (
                157963,
                157962,
                157961
            );
            ServiceDescription = Test;
            Speciality = 55;
            SpecialityName = Transport;
            UserFRPs = "<null>";
            Videos =             (
                                {
                    VideoId = "cRchvv_dB2c";
                    VideoLink = "http://www.youtube.com/watch?v=cRchvv_dB2c";
                    VideoType = YouTube;
                },
                                {
                    VideoId = "onvkllwM-OI";
                    VideoLink = "http://www.youtube.com/watch?v=onvkllwM-OI";
                    VideoType = YouTube;
                },
                                {
                    VideoId = DGVJtAHzzDQ;
                    VideoLink = "http://www.youtube.com/watch?v=DGVJtAHzzDQ";
                    VideoType = YouTube;
                }
            );
        },
                {
            ApprovalStatus = Unapproved;
            CurrencyCode = "<null>";
            Packages = "<null>";
            Photos = "<null>";
            ServiceDescription = Baby;
            Speciality = 5;
            SpecialityName = "Children/Babies Photographer";
            UserFRPs = "<null>";
            Videos =             (
                                {
                    VideoId = "cRchvv_dB2c";
                    VideoLink = "http://www.youtube.com/watch?v=cRchvv_dB2c";
                    VideoType = YouTube;
                },
                                {
                    VideoId = DGVJtAHzzDQ;
                    VideoLink = "http://www.youtube.com/watch?v=DGVJtAHzzDQ";
                    VideoType = YouTube;
                }
            );
        },
}

I want all null values to be replace by empty string.

Upvotes: 1

Views: 2758

Answers (5)

Ahmed Abdallah
Ahmed Abdallah

Reputation: 2355

The short code you can use here:-

   NSString * newValue=[self isNotNull:[your Object here]]  ? [your Object here] : @"Value that you want to replace";
    - (BOOL)isNull:(NSObject *)object {
        if (!object) return YES;
        else if (object == [NSNull null]) return YES;
        else if ([object isKindOfClass:[NSString class]]) {
            return ([((NSString *)object)isEqualToString : @""]
                    || [((NSString *)object)isEqualToString : @"null"]
                    || [((NSString *)object)isEqualToString : @"<null>"]
                    || [((NSString *)object)isEqualToString : @"(null)"]
                    );
        }
        return NO;
    }

    - (BOOL)isNotNull:(NSObject *)object {
        return ![self isNull:object];
    }

Upvotes: 0

mbi
mbi

Reputation: 629

This is how we do it

@interface NSMutableArray (JSON)

- (void)recursivelyRemoveNulls;

@end

@implementation NSMutableArray (JSON)

- (void)recursivelyRemoveNulls
{
    [self enumerateObjectsUsingBlock:^(id value, NSUInteger __unused idx, BOOL __unused *nestedStop)
    {
        if ([value isKindOfClass:[NSDictionary class]])
        {
            NSMutableDictionary *modifiedValue = [NSMutableDictionary dictionaryWithDictionary:value];
            [modifiedValue recursivelyRemoveNulls];
            [self removeObject:value];
            [self addObject:modifiedValue];
        }
        else if ([value isKindOfClass:[NSArray class]])
        {
            NSMutableArray *modifiedValue = [NSMutableArray arrayWithArray:value];
            [modifiedValue recursivelyRemoveNulls];
            [self removeObject:value];
            [self addObject:modifiedValue];
        }
    }];
}

@end

@interface NSMutableDictionary (JSON)

- (void)recursivelyRemoveNulls;

@end

@implementation NSMutableDictionary (JSON)

- (void)recursivelyRemoveNulls
{
    [self enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL __unused *stop)
    {
        if (value == [NSNull null] || value == nil)
        {
            [self removeObjectForKey:key];
        }
        else if ([value isKindOfClass:[NSDictionary class]])
        {
            NSMutableDictionary *modifiedValue = [NSMutableDictionary dictionaryWithDictionary:value];
            [modifiedValue recursivelyRemoveNulls];
            self[key] = modifiedValue;
        }
        else if ([value isKindOfClass:[NSArray class]])
        {
            NSMutableArray *modifiedValue = [NSMutableArray arrayWithArray:value];
            [modifiedValue recursivelyRemoveNulls];
            self[key] = modifiedValue;
        }
    }];
}

@end

Upvotes: 0

Sanjeet Verma
Sanjeet Verma

Reputation: 571

Try this this is mine code i am using i hope it would be helpful!!

 func checkDictionary(let dict:NSMutableDictionary)
{
        let keys = Array(dict.allKeys)
        for i in keys
        {
            let checkvalue = dict.valueForKey(i as! String)
            if checkvalue! .isKindOfClass(NSNull)
            {
                dict.setObject("", forKey: i as! NSString)
            }
            else if checkvalue!.isKindOfClass(NSDictionary)
            {
                let dic = checkvalue as! NSDictionary
                let dicts = dic.mutableCopy()
                self.checkDictionary(dicts as! NSMutableDictionary)
                dict.setObject(dicts, forKey: i as! NSString)
            }
            else if checkvalue! .isKindOfClass(NSArray)
            {
                let keys2 = checkvalue as! NSArray
                let keys1 = keys2.mutableCopy() as! NSMutableArray
                dict.setObject(keys1, forKey: i as! NSString)
                for j in keys1
                {
                    if j .isKindOfClass(NSNull)
                    {
                        keys1.replaceObjectAtIndex(keys1.indexOfObject(j), withObject:"")
                    }
                    if j.isKindOfClass(NSDictionary)
                    {
                        let dic = j as! NSDictionary
                        let dicts = dic.mutableCopy()
                        keys1.replaceObjectAtIndex(keys1.indexOfObject(j), withObject: dicts)
                        self .checkDictionary(dicts as! NSMutableDictionary)
                    }
                }
            }
        }
}

In objective-C Try this!!

 -(void)CheckDictionary:(NSMutableDictionary *)dic
{
    NSArray *Arr = [dic allKeys];
    for (int i = 0; i<Arr.count; i++)
    {
        if ([[dic valueForKey:[Arr objectAtIndex:i]] isKindOfClass:[NSNull class]])
        {
            [dic setObject:@"" forKey:[Arr objectAtIndex:i]];
        }
        else if ([[dic valueForKey:[Arr objectAtIndex:i]] isKindOfClass:[NSDictionary class]])
        {
            NSMutableDictionary *dict = [[dic valueForKey:[Arr objectAtIndex:i]] mutableCopy];
            [dic setObject:dict forKey:[Arr objectAtIndex:i]];
            [self CheckDictionary:dict];
        }
        else if ([[dic valueForKey:[Arr objectAtIndex:i]] isKindOfClass:[NSMutableArray class]])
        {
            NSMutableArray *Arr12 = [dic valueForKey:[Arr objectAtIndex:i]];
            for (int j = 0; j<Arr12.count; j++)
            {
                if ([[Arr12 objectAtIndex:j] isKindOfClass:[NSDictionary class]])
                {
                    NSDictionary *dict123 = [Arr12 objectAtIndex:j];
                    NSMutableDictionary *dict = [dict123 mutableCopy];
                    [Arr12 replaceObjectAtIndex:j withObject:dict];
                    [self CheckDictionary:dict];
                }
            }
        }
    }
}

And Just pass the whole dictionary when you call this method I hope it would be helpful!!

 NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options: NSJSONReadingMutableContainers error: nil];
             if (dictionary)
             {
                 NSMutableDictionary *dict = [dictionary mutableCopy];
                 [self CheckDictionary:dict];
                 dictionary = [NSDictionary dictionaryWithDictionary:dict];
             }

Upvotes: 0

arturdev
arturdev

Reputation: 11039

Then just do that

NSString *json = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:yourDictionary options:0 error:nil] encoding: NSUTF8StringEncoding];

NSString *jsonWithoutNulls = [json stringByReplacingOccurrencesOfString:@"<null>" withString:@""]; 
NSData *data = [jsonWithoutNulls dataUsingEncoding:NSUTF8StringEncoding] 
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

Upvotes: 3

user3600801
user3600801

Reputation:

I prefer to use Macros to determine null values.

#define IS_NULL(value) (value != nil && value != Nil && value != NULL && value != (id)[NSNull null])

and I invoke it like

if (IS_NULL(CurrencyCode))
{
//insert ""
}else
{
//do necessary updates
}

OR you can also use the following method ,

-(BOOL) isNull: (NSString*)value{
    if ([value isEqualToString:@"<null>"]){
        return  false;
    }
    return true;
}

and you can invoke it like,

if (isNull(currencyType))
{
//insert @""
}else{
//do necessary updates
}

Upvotes: 0

Related Questions