Ios 无法从JSON获取单个结果
我正在尝试使用Objective-C解析一个简单的JSON。 我的JSON文件如下所示:Ios 无法从JSON获取单个结果,ios,objective-c,json,Ios,Objective C,Json,我正在尝试使用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 dataWithContentsOfUR
{ "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
NSError*错误;
NSString*url_string=[NSString stringWithFormat:@”http://www.mywebsite.com/test"];
NSData*data=[NSData dataWithContentsOfURL:[NSURL URLWithString:url_string]];
NSMutableArray*json=[NSJSONSerialization JSONObjectWithData:数据选项:针织错误:&错误];
NSLog(@“我的->json:%@),json);
//NSString*str=json[0]// 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数据与URL:
的内容一起使用。使用NSURLSession
从远程URL获取数据。您的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数据与URL:
的内容一起使用。使用NSURLSession
从远程URL获取数据