Search code examples
iosios5

NSJSONSerialization can't handle null values


I have some code that looks like this:

NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
                                                     options:kNilOptions
                                                       error:&error];

NSArray *arrRequests = [NSJSONSerialization JSONObjectWithData:data
                                                       options:NSJSONReadingMutableContainers
                                                         error:nil];

// Loop through the array and generate the necessary annotation views
for (int i = 0; i<= arrRequests.count - 1; i++)
{
    //now let's dig out each and every json object
    NSDictionary *dict = [arrRequests objectAtIndex:i];

    NSString *is_private = [NSString
                            stringWithString:[dict objectForKey:@"is_private"]];
                            ...

It works when the value for is_private is 1 or 0, but if it is null it crashes with an exception on this line:

NSString *is_private = [NSString stringWithString:[dict objectForKey:@"is_private"]];

Is there a way to check if it is not null or handle this so that it is able to put nil into the NSString *is_private variable?

Thanks!


Solution

  • Your problem has nothing to do with NSJSONSerialization and everything to do with the fact that you're passing a nil value to stringWithString:. Why not just simply that line to NSString *is_private = [dict objectForKey:@"is_private"];?

    Also, why are you using an NSString to store a boolean value? An NSNumber would be much better-suited.