I have a JSON object that is coming from a webserver.
The log is something like this:
{
\"status\":\"success\",
\"Us
The best answer is what Aaron Hayman has commented below the accepted answer:
if ([tel isKindOfClass:[NSNull class]])
It doesn't produce a warning :)
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];
In Swift you can do:
let value: AnyObject? = xyz.objectForKey("xyz")
if value as NSObject == NSNull() {
// value is null
}