2012-08-01 108 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;