访问从NSJSONSerialization生成的NSDictionary中的JSON数据 [英] Accessing JSON data inside an NSDictionary generated from NSJSONSerialization
问题描述
在访问以下网址中的JSON数据时遇到一些问题( http://jamesstenson.com/portraits /?json = 1 ),基本上我想访问附件下面的完整网址。我的代码目前如下:
Having some trouble accessing the JSON data in the following URL ( http://jamesstenson.com/portraits/?json=1 ), basically I want to access the "full" "url"'s underneath "attachments". My code at the moment is as follows:
NSError *e = nil;
NSData *jsonFeed = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://jamesstenson.com/portraits/?json=1"]];
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:jsonFeed options:NSJSONReadingMutableContainers error: &e];
if (!jsonData) {
NSLog(@"Error parsing JSON: %@", e);
} else {
for(NSDictionary *item in [jsonData objectForKey:@"page"]) {
for(NSDictionary *attachment in [item objectForKey:@"images"]) {
NSLog(@"%@", attachment);
}
}
}
这不断引发错误:
2011-12-21 10:13:39.362 JSON[3463:f803] -[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x6a7b500
2011-12-21 10:13:39.363 JSON [3463:f803] * 由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:' - [__ NSCFString objectForKey:]:无法识别的选择器发送到实例0x6a7b500'
2011-12-21 10:13:39.363 JSON[3463:f803] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x6a7b500'
I我知道我错误地访问了这些项目,但无法弄清楚如何实现这一目标。我尝试了几种解决方案,例如 http://blogs.captechconsulting .com / blog / nathan-jones / getting-started-json-ios5 - 但没有运气。我是iOS开发的新手,对JSON有一点了解。感谢大家提前帮助。
I am aware I am accessing the items wrongly, but cannot figure out how to achieve this. I've tried several solutions such as http://blogs.captechconsulting.com/blog/nathan-jones/getting-started-json-ios5 - but no luck. I am complete newbie to iOS development and have a little knowledge of JSON. Thanks for everyones help in advance.
推荐答案
问题在于你的循环
for(NSDictionary *item in [jsonData objectForKey:@"page"])
你不会在item中获得NSDictionary,它会返回Dictionary的键,这将是NSString
You won't get NSDictionary in item, it will return you key of Dictionary, which would be NSString
检查此链接对于目标c中的每个循环,用于访问NSMutable词典知道如何遍历NSDictionay
Check this link for each loop in objective c for accessing NSMutable dictionary to know how to traverse through NSDictionay
以下是根据您的要求修改的代码,可能对您有帮助
Below is the modified code for your requirement, might help you
if (!jsonData) {
NSLog(@"Error parsing JSON: %@", e); } else {
NSArray *attachments = [[jsonData objectForKey:@"page"] objectForKey:@"attachments"];
for(NSDictionary *object in attachments) {
NSLog(@"%@", [object objectForKey:@"images"]);
NSLog(@"%@", [[[object objectForKey:@"images"] objectForKey:@"full"] objectForKey:@"url"]);
}
}
这篇关于访问从NSJSONSerialization生成的NSDictionary中的JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!