我正在尝试从我的wordpress博客解析JSON提要。我有一个我需要使用的自定义字段但无法使其与SBJson一起使用。这是我的饲料的样子(我剥夺了其他无用的东西):
{
"status":"ok",
"count":27,
"count_total":2552,
"pages":95,
"posts":[
{
"id":8978,
"type":"post",
"custom_fields":{
"btnNameScrollBlog":[
"<null>"
]
"author-name":[
"John Doe"
]
},
}
我正试图获得作者的名字。 这是我用于在iOS上获取Feed的代码:
-(void)downloadRecentPostJson{
[recentPost removeAllObjects];
[previous_total_per_page removeAllObjects];
NSURL *urls = [NSURL URLWithString:[NSString stringWithFormat:@"%@/?json=%@",url,methodJson]];
NSData *sa = [NSData dataWithContentsOfURL:urls];
NSString *jsonString = [[NSString alloc] initWithData:sa encoding:NSUTF8StringEncoding];
NSDictionary *result = [jsonString JSONValue];
NSArray* posts = [result objectForKey:@"posts"];
total_page = [[result objectForKey:@"pages"] intValue];
total_post_per_page = [[result objectForKey:@"count"] intValue];
[previous_total_per_page addObject:[result objectForKey:@"count"]];
current_page = 1;
for (NSDictionary *post in posts) {
id custom = [post objectForKey:@"custom_fields"];
id thumbnail = [post objectForKey:@"thumbnail"];
NSString *featuredImage = @"";
if (thumbnail != [NSNull null])
{
featuredImage = (NSString *)thumbnail;
}
else
{
featuredImage = @"0";
}
[recentPost addObject:[NSArray arrayWithObjects:[post objectForKey:@"id"],[post objectForKey:@"title_plain"],[post objectForKey:@"excerpt"],featuredImage,[post objectForKey:@"content"],[post objectForKey:@"date"],[post objectForKey:@"comments"],[post objectForKey:@"comment_status"],[post objectForKey:@"scrollBlogTemplate"],[post objectForKey:@"url"],[post objectForKey:@"specialBtn"],[post objectForKey:@"btnNameScrollBlog"],[post objectForKey:@"latScrollBlog"],[post objectForKey:@"longScrollBlog"],[post objectForKey:@"openWebUrlScrollBlog"],[post objectForKey:@"gallery"], [custom objectForKey:@"author-name"], nil]];
}
我尝试将custom_fields对象设置为id:id custom = [post objectForKey:@“custom_fields”];
然后使用它来获取作者的名字:[custom objectForKey:@“author-name”]
但我得到一个NSInvalidArgumentException',原因:' - [__ NSArrayM rangeOfString:]:无法识别的选择器错误。
有什么建议吗?
如果我尝试从帖子中获取类别标题怎么办?
"categories": [
{
"id": 360,
"slug": "deals",
"title": "Deals",
"description": "",
"parent": 0,
"post_count": 28
}
],
我是否将类别放在这样的数组中?我如何从中获得标题?我尝试了这个并将对象放在索引3处,但是出现了错误。
NSArray *cat = [post objectForKey:@"categories"];
答案 0 :(得分:3)
'-[__NSArrayM rangeOfString:]: unrecognized selector error.
表示您将数组视为字符串。您的代码几乎是正确的,您只需要从数组中获取第一个项目(最好检查数组是否为空),因为
"author-name":[
"John Doe"
]
是一个包含一个字符串的数组。所以:
NSArray *names = [custom objectForKey:@"author-name"];
NSString *name = [names firstObject];
NSArray *categories = [custom objectForKey:@"categories"];
NSDictionary *category = [categories firstObject];
NSString *title = [category objectForKey:@"title"];