GeekedOut
GeekedOut

Reputation: 17185

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!

Upvotes: 2

Views: 2202

Answers (3)

Luke
Luke

Reputation: 487

You should be able to handle it like so:

id value = [dict valueForKey:@"is_private"];
NSString *is_private = [value isEqual:[NSNull null]] ? nil : value;

Upvotes: 4

oltman
oltman

Reputation: 1792

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.

Upvotes: 1

kevboh
kevboh

Reputation: 5245

Why don't you just check if [dict objectForKey:@"is_private"] is nil or [NSNull null] before passing it to stringWithString:?

Upvotes: 1

Related Questions