I want to get data from JSON service. Only iOS 7 version crash when get data from JSON value. It returns from JSON service below that:
{
voteAverageRating =
Put a check before accessing the value from JSON like,
if([NSNull null] != [listDic objectForKey:@"voteCount"]) {
NSString *voteCount = [listDic objectForKey:@"voteCount"];
/// ....
}
Reason for checking is, collection objects like NSDictionary
do not allow values to be nil
, hence they are stored as null. Passing intValue
to a NSNull
will not work as it will not recognise this selector.
Hope that helps!
That's quite normal. JSON can send null values to your app. If it does, then this is done intentionally by the server and it expects you to handle it. Figure out what the correct behaviour is when a null value is received. Then when you get an object that could be a null value, check
if (object == [NSNull null])
{
// stuff to handle null objects
}
else
{
// stuff to handle non-null objects
}
The real problem isn't that your app crashes, but that your app doesn't handle JSON data that it is supposed to handle.
As the others have said, JSON null will be deserialized to NSNull
. Unlike nil
, You cannot send (most) messages to NSNull
.
One solution is to add an implementation of -intValue on NSNull via category:
@implementation NSNull (IntValue)
-(int)intValue { return 0 ; }
@end
Now your code will work since sending -intValue
to NSNull
will now return 0
Another option: You could also add an "IfNullThenNil" category to NSObject...
@implementation NSObject (IfNullThenNil)
-(id)ifNullThenNil { return self ; }
@end
@implementation NSNull (IfNullThenNil)
-(id)ifNullThenNil { return nil ; }
@end
Now, your code becomes:
int voteCount = [[[listDic objectForKey:@"voteCount"] ifNullThenNil] intValue] ;
Just add a call to -ifNullThenNil
wherever you access values from a JSON object.
For me this is worked
NSArray* merStore = [tmpDictn objectForKey:@"merchantStore"];
if ([merStore isKindOfClass:[NSArray class]] && merStore.count !=0)
{
for(int n = 0; n < merStore.count; n++)
{
NSMutableDictionary *storeDic = [merStore objectAtIndex:n];
[latitudeArray addObject:[storeDic objectForKey:@"latitude"]];
}
}
I hope it helps some one. If you need any help let me know.