Checking a null value in Objective-C that has been returned from a JSON string

前端 未结 15 1422
北海茫月
北海茫月 2020-11-30 20:34

I have a JSON object that is coming from a webserver.

The log is something like this:

{          
   \"status\":\"success\",
   \"Us         


        
相关标签:
15条回答
  • 2020-11-30 21:04

    <null> is how the NSNull singleton logs. So:

    if (tel == (id)[NSNull null]) {
        // tel is null
    }
    

    (The singleton exists because you can't add nil to collection classes.)

    0 讨论(0)
  • 2020-11-30 21:05

    Best would be if you stick to best practices - i.e. use a real data model to read JSON data.

    Have a look at JSONModel - it's easy to use and it will convert [NSNUll null] to * nil * values for you automatically, so you could do your checks as usual in Obj-c like:

    if (mymodel.Telephone==nil) {
      //telephone number was not provided, do something here 
    }
    

    Have a look at JSONModel's page: http://www.jsonmodel.com

    Here's also a simple walk-through for creating a JSON based app: http://www.touch-code-magazine.com/how-to-make-a-youtube-app-using-mgbox-and-jsonmodel/

    0 讨论(0)
  • 2020-11-30 21:08

    If you are dealing with an "unstable" API, you may want to iterate through all the keys to check for null. I created a category to deal with this:

    @interface NSDictionary (Safe)
    -(NSDictionary *)removeNullValues;
    @end
    
    @implementation NSDictionary (Safe)
    
    -(NSDictionary *)removeNullValues
    {
        NSMutableDictionary *mutDictionary = [self mutableCopy];
        NSMutableArray *keysToDelete = [NSMutableArray array];
        [mutDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            if (obj == [NSNull null]) 
            {
                [keysToDelete addObject:key];
            }
        }];
        [mutDictinary removeObjectsForKeys:keysToDelete];
        return [mutDictinary copy];
    }
    @end
    
    0 讨论(0)
  • 2020-11-30 21:08

    I tried a lot method, but nothing worked. Finally this worked for me.

    NSString *usernameValue = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"usernameKey"]];
    
    if ([usernameValue isEqual:@"(null)"])
    {
         // str is null
    }
    
    0 讨论(0)
  • 2020-11-30 21:10

    you can also check this Incoming String like this way also:-

    if(tel==(id) [NSNull null] || [tel length]==0 || [tel isEqualToString:@""])
    {
        NSlog(@"Print check log");
    }
    else
    {  
    
        NSlog(@Printcheck log %@",tel);  
    
    }
    
    0 讨论(0)
  • 2020-11-30 21:14

    Here is the example with the cast:

    if (tel == (NSString *)[NSNull null])
    {
       // do logic here
    }
    
    0 讨论(0)
提交回复
热议问题