【问题标题】:Cannot get single result from JSON无法从 JSON 获得单个结果
【发布时间】:2018-03-09 03:10:10
【问题描述】:

我正在尝试使用 Objective-C 解析一个简单的 JSON。 我的 JSON 文件如下所示:

{ "videosource": "hello my value" }

还有我的 iOS Objective-C 代码:

NSError *error;
NSString *url_string = [NSString stringWithFormat: @"http://www.mywebsite.com/test"];
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:url_string]];
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(@"my -> json: %@", json);

//NSString *str = json[0]; //<- this one doest not work it makes app crush
//__NSSingleEntryDictionaryI objectAtIndexedSubscript:]: unrecognized selector sent to instance

//NSUInteger num = 0;
//NSString *str = [json objectAtIndex:num]; <- this one doest not work it makes app crush

我正在尝试从 JSON 的 videosource 键中获取值。怎么做?

【问题讨论】:

    标签: ios objective-c json


    【解决方案1】:

    您的 JSON 是字典,而不是数组。 { } 表示字典。 [ ] 表示数组。很简单。

    NSError *error = nil;
    NSString *url_string = @"http://www.mywebsite.com/test";
    NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:url_string]];
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    if (json) {
        NSString *source = json[@"videosource"];
    } else {
        NSLog(@"Error parsing JSON: %@", error);
    }
    

    另外,你真的不应该使用NSData dataWithContentsOfURL:。使用NSURLSession 从远程 URL 获取数据。

    【讨论】:

      猜你喜欢
      • 2011-10-21
      • 2015-01-10
      • 1970-01-01
      • 2012-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多