用Objective-c解析JSON?
我的目标是使用Objective-C解析JSON。我已成功获取JSON,但在尝试解析文本时,我收到一个发送到实例的用Objective-c解析JSON?,objective-c,json,Objective C,Json,我的目标是使用Objective-C解析JSON。我已成功获取JSON,但在尝试解析文本时,我收到一个发送到实例的无法识别的选择器。如何获取每个键的值“author”,“author\u flair\u type”等,并将该值转换为字符串对象 下面是我用来从URL获取JSON的代码: int main(int argc, char *argv[], char *envp[]) { NSError *error; NSString *url_string = [NSString
无法识别的选择器。如何获取每个键的值“author”
,“author\u flair\u type”
等,并将该值转换为字符串对象
下面是我用来从URL获取JSON的代码:
int main(int argc, char *argv[], char *envp[]) {
NSError *error;
NSString *url_string = [NSString stringWithFormat: @"https://api.pushshift.io/reddit/search/submission/?sort_type=created_utc&subreddit=rasberry_pi"];
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:url_string]];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
return 0;
}
JSONObjectWithData的返回值可能是字典,而不是数组。对象可能包含一个数组。您可以尝试以下方法:
if (responseStatusCode == 200) {
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data //1
options:NSJSONReadingAllowFragments
error:&error];
NSMutableArray *maAnimalsList = [[NSMutableArray alloc] init];
for(id key in json) {
[maAnimalsList addObject:key];
}
}
顺便说一句,您应该知道dataWithContentsOfURL
方法是同步网络操作。显示实际导致错误的代码。请注意,JSON是一个字典,而不是一个数组。
if (responseStatusCode == 200) {
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data //1
options:NSJSONReadingAllowFragments
error:&error];
NSMutableArray *maAnimalsList = [[NSMutableArray alloc] init];
for(id key in json) {
[maAnimalsList addObject:key];
}
}
int main(int argc, char *argv[], char *envp[]) {
NSError *error;
NSString *url_string = [NSString stringWithFormat:@"https://api.pushshift.io/reddit/search/submission/?sort_type=created_utc&subreddit=rasberry_pi"];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url_string]];
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (error) {
NSLog(@"error: %@", error);
return 1;
}
NSArray *entities = result.allValues.firstObject;
for (NSDictionary *dict in entities) {
NSLog(@"author: %@, author_flair_type: %@", dict[@"author"], dict[@"author_flair_type"]);
}
return 0;
}