在NSDictionary / NSArray中使用空字符串检查并替换所有空值

问题描述 投票:1回答:5

我将我的json响应存储在NSDictionary中,这个字典包含各种array,所以我想用@""空字符串替换所有空值。

{
    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;
                }
            );
        },
}

我希望所有空值都替换为空字符串。

ios objective-c null nsdictionary
5个回答
1
投票

然后就这样做

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];

0
投票

我更喜欢使用宏来确定空值。

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

我就像调用它一样

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

或者你也可以使用以下方法,

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

你可以调用它,就像

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

0
投票

试试这个是我正在使用的我的代码我希望它会有所帮助!!

 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)
                    }
                }
            }
        }
}

在Objective-C试试这个!!

 -(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];
                }
            }
        }
    }
}

当你调用这个方法时,只需传递整个字典,我希望它会有所帮助!

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

0
投票

这是我们的做法

@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

0
投票

你可以在这里使用的短代码: -

   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];
    }
© www.soinside.com 2019 - 2024. All rights reserved.