PDA

View Full Version : How to handle JSON response in case of null




Narendar Singh
Sep 13, 2012, 04:37 PM
My server is responding some json like below:

"MyData":
[
{
"name": "narendar",
"address": "san rafael"
}
]

some times I get null in name param:

"MyData":
[
{
"name": null,,
"address": "san rafael"
}
]

I am displaying these tow values in two UITextView like below:

if ([myArray objectForKey:@"name"])
{
self.name.text = [myArray objectForKey:@"name"];
}

then my code get crashed if name comes with null,.

To handle this situation I have changed my code like below and its working now:

if ([myArray objectForKey:@"category"] != [NSNull null])
{
// body skips for null, and this code doesn't executes.
self.name.text = [selectedDeal objectForKey:@"name"];
}

Now my question is do I need to compare objectForKey with [NSNull null] ?

Please let me know how to handle this situation when server sends null,, at least it should not be crashed.



PhoneyDeveloper
Sep 13, 2012, 06:51 PM
You don't say what you mean by "crash." Most likely you are getting a runtime exception and SIGABRT due to using NSNull null where an NSString* should go.

All the JSON parsers insert NSNull null if the JSON value is null. So you need to avoid code that ends up like this

self.name.text = [NSNull null];

That code will probably cause a SIGABRT error, which looks like a crash. To avoid that problem you need to check if the value returned from the JSON is NSNull null.

idelovski
Sep 14, 2012, 10:35 AM
JSON was the main reason why I have these 4 categories. Now I use them all the time where I exchange data between internal classes and web/databases.

#pragma mark -
#pragma mark NSDictionary (nullObjects)
#pragma mark -

@implementation NSMutableDictionary (nullObjects)

- (void)setObjectOrNull:(id)anObject forKey:(id)aKey;
{
id goodObject = anObject ? anObject : [NSNull null];

[self setObject:goodObject forKey:aKey];
}

@end

@implementation NSDictionary (nullObjects)

- (id)objectOrNilForKey:(id)aKey;
{
id anObject = [self objectForKey:aKey];

if (anObject == [NSNull null])
return (nil);

return (anObject);
}

@end

#pragma mark -
#pragma mark NSArray (nullObjects)
#pragma mark -

@implementation NSMutableArray (nullObjects)

- (void)addObjectOrNull:(id)anObject;
{
id goodObject = anObject ? anObject : [NSNull null];

[self addObject:goodObject];
}

@end

@implementation NSArray (nullObjects)

- (id)objectOrNilAtIndex:(int)idx;
{
id anObject = [self objectAtIndex:idx];

if (anObject == [NSNull null])
return (nil);

return (anObject);
}

@end