我有一个像这样的json数组:
"posts": [
{
"id": 917,
"tags": [
{
"id": 39
}
]
},
{
"id": 918,
"tags": [
{
"id": 38
}
]
}
]
我已经获得了帖子ID,但无法获得帖子标记ID 需要获取每个帖子的数据,例如邮政917(标签39),邮政918(标签38)。
我使用github的Jsonloader,链接:github.com/Phillipus/JSONHandler
答案 0 :(得分:0)
我认为json的格式是错误的。它应该是这样的: -
"posts":[{"id":917,"tags":39},{"id":918,"tags":38}]
这是一个包含两个字典对象的数组。然后,您可以使用
获取对象NSArray * postArray = [json objectForKey:@"posts"];
NSDictionary * firstObject = [postArray firstObject];
NSNumber * id1 = [firstObject objectForKey:@"id"];
NSArray * tags1 = [firstObject objectForKey:@"tags"];
NSNumber* tag1 = [[tags firstObject] objectForKey:@"id"];
试试这个。
更新回答:
NSArray * postArray = [json objectForKey:@"posts"];
for(int i=0;i<postArray.count;i++){
NSDictionary * postObject = [postArray objectAtIndex:i];
NSNumber * postId = [postObject objectForKey:@"id"];
NSLog(@"PostID:%@",postId);
NSArray * postTag = [postObject objectForKey:@"tags"];
for(int j=0;j<postTag.count;j++){
NSDictionary * postTagIdDic = [postTag objectAtIndex:j];
NSNumber * postTagId = [postTagIdDic objectForKey:@"id"];
NSLog(@"postTagId:%@",postTagId);
}
}
答案 1 :(得分:0)
你可以用这个
NSError *error=nil;
id json=[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
if (!error) {
NSLog(@"json:%@",json);
NSArray *a=[[json objectForKey:@"posts"] copy];
NSArray *tags=[[a objectAtIndex:0] copy];
NSLog(@"%@",[NSStrig stringWithFormat:@"%@",[[tags objectAtIndex:0] objectForKey:@"id"]]);
[a release];
}