OGeek|极客世界-中国程序员成长平台

标题: iOS,JSON检查值是否为假或字符串 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 13:24
标题: iOS,JSON检查值是否为假或字符串

我需要检查我的值是否包含“false”或字符串。

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);

image = 0;

我有一个 UICollectionView,我想在其中设置来自 URL 的图像。 如果 "image"的值为 false,我想放另一张图片,但我不知道如何检查它是否为 false。

- (UICollectionViewCell *)collectionViewUICollectionView *)collectionView cellForItemAtIndexPathNSIndexPath *)indexPath {
    if ([[[content objectForKey"name"] objectAtIndex:indexPath.row] objectForKey"image"] == nil)

我也试过 "== false""== 0"但没有任何效果。

有人有想法吗?



Best Answer-推荐答案


拆分您的代码,使其更易于阅读和调试。似乎“图像”的值要么是 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
}

关于iOS,JSON检查值是否为假或字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27606790/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4