سؤال

I have a json array like this:

"posts": [
    {
        "id": 917,
        "tags": [
            {
                "id": 39
            }
        ]
    },
    {
        "id": 918,
        "tags": [
            {
                "id": 38
            }
        ]
    }
]

I've already get post id, but can't get the post tags id Need to get data for each post, ex. Post 917 (tag 39), Post 918 (tag 38).

I use the Jsonloader from github, link: github.com/Phillipus/JSONHandler

هل كانت مفيدة؟

المحلول

I think the format for json is wrong. It should be something like:-

"posts":[{"id":917,"tags":39},{"id":918,"tags":38}]

This is an array of one 2 dictionary objects. Then, you can get the objects using

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"];

Try this out.

Updated answer:

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);
    }
}

نصائح أخرى

you can use this

    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];

    }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top