2014-12-22 35 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

相關問題