I have a JSON object that is coming from a webserver.
The log is something like this:
{
\"status\":\"success\",
\"Us
<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.)
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/
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
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
}
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);
}
Here is the example with the cast:
if (tel == (NSString *)[NSNull null])
{
// do logic here
}