【发布时间】:2017-07-21 08:02:31
【问题描述】:
我正在制作这个从 url 获取一些数据的应用程序(审查)。问题是我没有找到获取 PHP 脚本回显的解决方案。
从该脚本返回的正常数组如下所示:
{"user_data": {"id":"78","image":"https://www.i********p.com/uploads/ideas/fun/2017/03/28/78.jpg","idea":"Join Facebook groups related to your passions or hobbies and meet friends.","owner_ID":"1","owner":"Eduard","owner_photo":"https://www.i********p.com/uploads/members/1/1.png","rating":"4","reviews":"1 review","msg":"success"}}
问题是如何使用 Objective-c(没有循环)从“user_data”访问这个数组的每个值?
Objective-c 代码:
- (void)getJSON {
NSError *error;
NSString *url_string = [NSString stringWithFormat: @"https://www.app.i******o.com/getidea.php?topic=%@", ideasTopic];
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:url_string]];
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (error) {
NSLog(@"Something went wrong: %@", error);
} else {
NSLog(@"json: %@", json);
NSLog(@"IMAGE: %@", [[json getObjectAtIndex:0] getObjectForKey:@"image"]);
}}
【问题讨论】:
-
[[json getObjectForKey: "user_data"] getObjectForKey:@"image"] 告诉我错误是什么
-
同样的错误,但这次是针对 'getObjectForKey'
-
在
NSArray或NSMutableArray的任意索引处获取任意对象的实例方法是objectAtIndex:。您在方法名称之前使用了一个额外的 get。但是,您的json被反序列化为NSDictionary,objectAtIndex将无法访问。请参阅下面的答案。 -
我试过这个没有构建问题,控制台告诉我无法识别的选择器实例。代码:NSLog(@"IMAGE: ℅@", [[json objectAtIndex:0] objectForKey:@"image"]);
-
首先将您的
json变量类型更改为NSDictionary,然后访问您的数据,例如:json[@"user_data"][@"image"]。
标签: ios objective-c json xcode