【问题标题】:How do I get certain value from Json in iOS? [closed]如何从 iOS 中的 Json 获得一定的价值? [关闭]
【发布时间】:2014-11-16 06:42:18
【问题描述】:

当我搜索This Link to JSON file 时,它不会返回任何内容(resultCount = 0)。这是我正在尝试做的一些代码。

NSData *data = [[NSData alloc] initWithContentsOfURL:@"https://itunes.apple.com/search?term=EMINEMLFLOCKAFLOCKA&entity=song&limit=3" options:NSDataReadingUncached error:&error];
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSString *resultCount = [JSON valueForKey:@"resultCount"];

// Does not return anything
NSLog(@"%@", resultCount);

我不明白为什么 resultCount 不返回任何内容。这段代码不存储它的值(0)吗?如何从 resultCount 中检索数据?我正在尝试从中获取 0、1、2 或 3 之类的值。

【问题讨论】:

  • “resultCount 不返回任何内容”是什么意思? resultCountNSNumber(但您错误地将其用作 NSString)。这不是一个函数。你希望它“回归”什么?如何? 您是否查看了此 URL 传递的 JSON 并意识到 resultCount 确实为 0?
  • A) 你确认data 是非空的吗? B) 你确认JSON 是非空的吗? C) 你为什么不使用error 参数? D) 为什么不向我们展示JSON 中的值?
  • @TheParamagneticCroissant 它显示数据中没有任何内容(如果 !data 的语句运行)。这是否意味着我无法获得 resultCount 值?
  • @abc123abc 表示initWithContentsOfURL 失败。检查什么是 int error
  • 如果data 中没有任何内容,那么error 中就有内容。但你不会抛弃那个,是吗?

标签: ios objective-c json nsstring nsdata


【解决方案1】:

我很惊讶你没有收到编译器警告(和崩溃),但你有两个问题:

  1. 您不能将initWithContentsOfUrlNSString 一起传递,您必须将其传递给NSURL
  2. 您应该将resultCount 解析为NSInteger 而不是NSString

固定:

NSError* error = [NSError new];
NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"https://itunes.apple.com/search?term=EMINEMLFLOCKAFLOCKA&entity=song&limit=3"] options:NSDataReadingUncached error:&error];
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSInteger resultCount = [[JSON valueForKey:@"resultCount"] intValue];

// Logs 0
NSLog(@"%ld", resultCount);

【讨论】:

    猜你喜欢
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    相关资源
    最近更新 更多