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

前端 未结 15 1424
北海茫月
北海茫月 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:27

    The best answer is what Aaron Hayman has commented below the accepted answer:

    if ([tel isKindOfClass:[NSNull class]])
    

    It doesn't produce a warning :)

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

    if you have many attributes in json, using if statement to check them one by one is troublesome. What even worse is that the code would be ugly and hard to maintain.

    I think the better approach is creating a category of NSDictionary:

    // NSDictionary+AwesomeDictionary.h
    
    #import <Foundation/Foundation.h>
    
    @interface NSDictionary (AwesomeDictionary)
    - (id)validatedValueForKey:(NSString *)key;
    @end
    
    // NSDictionary+AwesomeDictionary.m
    
    #import "NSDictionary+AwesomeDictionary.h"
    
    @implementation NSDictionary (AwesomeDictionary)
    - (id)validatedValueForKey:(NSString *)key {
        id value = [self valueForKey:key];
        if (value == [NSNull null]) {
            value = nil;
        }
        return value;
    }
    @end
    

    after importing this category, you can:

    [json validatedValueForKey:key];
    
    0 讨论(0)
  • 2020-11-30 21:27

    In Swift you can do:

    let value: AnyObject? = xyz.objectForKey("xyz")    
    if value as NSObject == NSNull() {
        // value is null
        }
    
    0 讨论(0)
提交回复
热议问题