2

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!

nevan king
  • 112,709
  • 45
  • 203
  • 241
GeekedOut
  • 16,905
  • 37
  • 107
  • 185

3 Answers3

4

You should be able to handle it like so:

id value = [dict valueForKey:@"is_private"];
NSString *is_private = [value isEqual:[NSNull null]] ? nil : value;
Luke
  • 477
  • 4
  • 9
1

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

kevboh
  • 5,207
  • 5
  • 38
  • 54
1

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.

oltman
  • 1,772
  • 1
  • 14
  • 24
  • got it! I saw the stringWithString in an example, and didn't pay much attention to it. What is it meant to be there for? Thanks! I'll accept your answer when StackOverflow allows me to do that. – GeekedOut Aug 01 '12 at 16:28
  • To be quite honest, I've never used it. You certainly aren't the first to ask this question :) http://stackoverflow.com/questions/1616348/nsstring-stringwithstring-whats-the-point – oltman Aug 01 '12 at 16:35