简体   繁体   中英

How to avoid the null array from json values?

 if(arrSubCategory.count>0||arrSubCategory!=Nil)
            {
            for (NSDictionary *dicsub in arrSubCategory)
            {
                [dicSubCategory setObject:[dicsub objectForKey:@"category_id"] forKey:@"category"];
                [dicSubCategory setObject:[dicsub objectForKey:@"parent_id"] forKey:@"parent"];
                [dicSubCategory setObject:[dicsub objectForKey:@"image"] forKey:@"image"];
                [dicSubCategory setObject:[dicsub objectForKey:@"name"] forKey:@"name"];
                  NSLog(@"sub category parsing%@",dicSubCategory);
                [file addSubCategories:dicSubCategory];
            }

here i am checking the array count is greater than zero then the condition have to check.

->but what happens mean

(
  ()
)

one empty array has been get storing in my array,how to avoid this empty from my json values.

You can check the object in arr is NSDictionary or not

 for (NSDictionary *dicsub in arrSubCategory) 
 {
     if([dicsub isKindOfClass:[NSDictionary class]])
     {
            [dicSubCategory setObject:[dicsub objectForKey:@"category_id"] forKey:@"category"];
            [dicSubCategory setObject:[dicsub objectForKey:@"parent_id"] forKey:@"parent"];
            [dicSubCategory setObject:[dicsub objectForKey:@"image"] forKey:@"image"];
            [dicSubCategory setObject:[dicsub objectForKey:@"name"] forKey:@"name"];
            NSLog(@"sub category parsing%@",dicSubCategory);
            [file addSubCategories:dicSubCategory];
     }
 }

You are checking if Object is nil, you should check if its count is zero.

Try this way :

NSArray *arr = [DicWholeCategories objectForKey:@"subcategory"];

if(arr.count > 0)
{
   [arrSubCategory addObject:arr];
}

Lots of Mistakes:

First of all your condition is wrong. It should be

if(arrSubCategory.count > 0 && !arrSubCategory)

You will need an && operator here instead of || because both condition should be true means array count should be greater than 0 and it should not be nil to proceed.

Comparison of an object with Nil is also wrong it should be nil .

Second thing don't compare any object with nil like (object != nil) better to use just (!object) .

Last thing if you want to check the object is null or not use isKindOfClass: method which returns a BOOL value.

if (![arrSubCategory isKindOfClass:[NSNull class]])

Well to avoid the empty array just one line is enough:

if ([arrSubCategory count] > 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM