AwYiss
AwYiss

Reputation: 49

iOS, JSON check if value is false or string

I need to check if my value contains "false" or a string.

JSON:

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

My Code:

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

NSLog shows me for the first image value:

 NSLog(@"%@", content);

image = 0;

I have a UICollectionView where I want to set an image from the URL. If the value "image" is false, i want to put an other image, but i dont know how to check if it is false.

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

I also tried "== false" "== 0" but nothing worked.

Anyone has an idea?

Upvotes: 2

Views: 362

Answers (2)

rmaddy
rmaddy

Reputation: 318814

Split your code up to make it easier to read and debug. And it seems the value of "image" will either be a bool (as an NSNumber) or a url (as an 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
}

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

When false comes in JSON, it gets deserialized as NSNumber with Boolean false inside it. You can do your comparison as follows:

// 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
}

Upvotes: 0

Related Questions