[英]Parsing JSON with Objective-c?
My goal is to parse pushshift.io's JSON using Objective-C. 我的目标是使用Objective-C解析pushshift.io的 JSON。 I have successfully fetched the JSON, but I receive an
unrecognized selector sent to instance
error when attempting to parse the text. 我已经成功获取了JSON,但是在尝试解析文本时收到
unrecognized selector sent to instance
,该unrecognized selector sent to instance
错误。 How do I get the value for each key "author"
, "author_flair_type"
, etc, and turn that value into a string object? 如何获取每个键
"author"
, "author_flair_type"
等的值,然后将该值转换为字符串对象?
Here is an example of the JSON: 这是JSON的示例:
{
"data": [
{
"all_awardings": [],
"author": "Le-Dragoon",
"author_flair_css_class": null,
"author_flair_richtext": [],
"author_flair_type": "text"
},
{
"all_awardings": [],
"author": "Shiroi_Kage",
"author_flair_css_class": null,
"author_flair_richtext": [],
"author_flair_text": null,
"author_flair_type": "text"
}
]
}
Here is the code I am using to fetch JSON from a URL: 这是我用来从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;
}
The return value of JSONObjectWithData will likely be a dictionary, not an array. JSONObjectWithData的返回值可能是字典,而不是数组。 The object may contain an array.
该对象可能包含一个数组。 You could try something like:
您可以尝试类似:
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;
}
BTW, you should aware that the dataWithContentsOfURL
method is synchronized network operation. 顺便说一句,您应该知道
dataWithContentsOfURL
方法是同步的网络操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.