2014-12-22 34 views
2

我需要检查我的值是否包含“false”或字符串。iOS,JSON检查值是否为假或字符串

JSON:

{"success":true,"name":[{"image":false},{"image":"https:\/\/www.url.com\/image.png"}]} 

我的代码:

NSData *contentData = [[NSData alloc] initWithContentsOfURL:url]; 
NSDictionary *content = [NSJSONSerialization JSONObjectWithData:contentData options:NSJSONReadingMutableContainers error:&error]; 

的NSLog显示我用于第一图像值:

NSLog(@"%@", content); 

图像= 0;

我有一个UICollectionView,我想从URL设置图像。 如果值“图像”是错误的,我想把其他图像,但我不知道如何检查它是否是假的。

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { 
    if ([[[content objectForKey:@"name"] objectAtIndex:indexPath.row] objectForKey:@"image"] == nil) 

我也试过“== false”“== 0”,但没有任何工作。

任何人有想法?

+1

“false”(当不用引号括起来)作为一个NSNumber编码一个零值。 –

回答

0

false进来JSON,它被反序列化为NSNumber其布尔false里面。您可以按照以下方式进行比较:

// This is actually a constant. You can prepare it once in the static context, 
// and use everywhere else after that: 
NSNumber *booleanFalse = [NSNumber numberWithBool:NO]; 
// This is the value of the "image" key from your JSON data 
id imageObj = [[[content objectForKey:@"name"] objectAtIndex:indexPath.row] objectForKey:@"image"]; 
// Use isEqual: method for comparison, instead of the equality check operator == 
if ([booleanFalse isEqual:imageObj]) { 
    ... // Do the replacement 
} 
1

拆分代码,使其更易于阅读和调试。而且“图片”的价值似乎是bool(作为NSNumber)或url(作为NSString)。

NSArray *nameData = content[@"name"]; 
NSDictionary *imageData = nameData[indexPath.row]; 
id imageVal = imageData[@"image"]; 
if ([imageVal isKindOfClass:[NSString class]]) { 
    NSString *urlString = imageVal; 
    // process URL 
else if ([imageVal isKindOfClass:[NSNumber class]) { 
    NSNumber *boolNum = imageVal; 
    BOOL boolVal = [boolNum boolValue]; 
    // act on YES/NO value as needed 
} 
+0

谢谢,这个作品也像dasblinkenlight的代码,但我只能接受一个答案。 – AwYiss

相关问题