【问题标题】:JSON parsing iOSJSON解析iOS
【发布时间】:2015-09-20 14:37:50
【问题描述】:

我在 iOS 应用程序中解析 JSON url 时遇到问题

NSString *strUrl = [NSString stringWithFormat:@"http://www.google.com/finance/info?q=NSE:MARUTI"];

NSURL *url = [NSURL URLWithString:strUrl];

NSData *stockData = [NSData dataWithContentsOfURL:url];
NSError *error;
NSMutableArray *arrStock = (NSMutableArray*)[NSJSONSerialization JSONObjectWithData:stockData options:kNilOptions error:&error];

链接返回一个数组,但我得到一个空数组。谁能帮忙

【问题讨论】:

  • 考虑接受有帮助的答案。要接受答案,请单击最佳答案旁边的空心复选标记,这样做会提高您的声誉并提供更多功能,请参阅reputation faq 更多详细信息,请参阅this page
  • 注意:将NSArray 转换为NSMutableArray 不会使其成为可变数组。而是使用 mutable copy: NSMutableArray *arrStock = [[NSJSONSerialization JSONObjectWithData:stockData options:kNilOptions error:&error] mutableCopy]; 或使用 NSJSONReadingMutableContainersNSJSONReadingMutableLeaves 等选项(如果它们满足需求)。

标签: ios json parsing


【解决方案1】:

返回的字符串不是有效的 JSON,因为它似乎以“//”开头。

有两件事可以帮助调试:

  1. 返回nil 时检查 (NSLog()) 错误返回。
    NSLog(@"error: %@", error.localizedDescription); 返回:

    错误:由于格式不正确,无法读取数据。

  2. NSLog返回的数据。
    NSLog(@"data : %@", stockData);

    数据: 注意前面的“0a2f2f20”。

  3. NSLog(@"data as string: %@", [[NSString alloc] initWithData:stockData encoding:NSUTF8StringEncoding]);

    字符串形式的数据:
    // [
    {
    “id”:“7152373”
    "t" : "马鲁蒂"

请注意前面的“//”前面有不明显的换行符,这就是我更喜欢十六进制表示的原因。

【讨论】:

  • Amazing Zaph.. 你帮助了我很多学习,因为我是 iOS 新手.. 干杯哥们
猜你喜欢
  • 1970-01-01
  • 2012-04-29
  • 2019-01-08
  • 1970-01-01
  • 2012-08-11
  • 2012-11-09
  • 2013-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多