2012-08-01 55 views
0

我有一些代码,看起来像这样:NSJSONSerialization不能处理空值

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"]]; 
          ... 

它工作时is_private值是1或0,但如果是null,则与此异常崩溃行:

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

有没有一种方法来检查,如果它不为空或处理这使得它能够把零到的NSString * is_private变量?

谢谢!

回答

1

您的问题与NSJSONSerialization无关并且与您将nil的值传递给stringWithString:的事实无关。为什么不只是简单的到NSString *is_private = [dict objectForKey:@"is_private"];

此外,为什么您使用NSString存储布尔值? NSNumber会更适合。

+0

得到它!我在一个例子中看到了stringWithString,并没有太注意它。这意味着什么?谢谢!当StackOverflow允许我这样做时,我会接受你的回答。 – GeekedOut 2012-08-01 16:28:43

+0

说实话,我从来没有用过它。你当然不是第一个问这个问题:) http://stackoverflow.com/questions/1616348/nsstring-stringwithstring-whats-thepoint – oltman 2012-08-01 16:35:09

1

为什么不在[dict objectForKey:@"is_private"]nil[NSNull null]之后才把它传递给stringWithString:

2

你应该能够处理它,像这样:

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