Reputation: 325
I have an string with the content below:a
{"friends":[
{"uid":25,"fbUid":100004063444823,"name":"Andressa Albuquerque","score":100},
{"uid":51,"fbUid":1297546080,"name":"Daniel Negri","score":5690}
]}
So I get the json code as NSArray with the code below:
NSError *jsonParsingError = nil;
NSData *friendsData = [friendsString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *friendsArray = [NSJSONSerialization JSONObjectWithData:friendsData options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError];
NSArray *friendsArrayFinal = [friendsArray valueForKey:@"friends"];
Until here is everything OK! But now I am trying to get all inner data... I need to take each "uid", "fbId" and "name" data inside a loop, but I don't know how to do that!
If I use the code below, I see that I am in the right way. But I don't know how to get a "item" property.
for(NSDictionary *item in friendsArrayFinal)
{
NSLog(@"Item: %@", item);
}
Upvotes: 0
Views: 2562
Reputation: 1520
First. Don't use objectForKey,ArrayForKey,BoolForKey or any thing like that. Modern Objective-C syntax provides a simple, readable, key indexing notation. Use that.
It looks like this
dict[@"key"];
you can of course pass a string variable instead of a literal
NSString * key = @"MY_SECRET_SUPER_LONG_KEY_THAT_I_DONT_WANT_TO_TYPE";
dict[key];
Second:
If you know they keys you want to access then you should just access them by name
for(NSDictionary *friend in friendsArrayFinal) {
friend[@"uid"];
friend[@"fbUid"];
friend[@"name"];
friend[@"score"];
}
If you do not know the potential keys or some of them may be missing then you can iterate through the keys
for(NSDictionary *friend in friendsArrayFinal) {
for(NSString * key in friend) {
NSlog(@"key: %@",key);
NSlog(@"value: %@",friend[key]);
}
}
Bonus Answer:
If you do dict[@"keyThatIsNotInDict"]
and the key is not in the dict you will get nil as the result.
Upvotes: 1
Reputation: 3928
Use this code:
NSDictionary *results=[NSJSONSerialization JSONObjectWithData:friendsData options:NSJSONReadingMutableLeaves error:nil];
if([[results valueForKey:@"friends"] isKindOfClass:[NSArray class]])
{
for(int i=0;i<[[results valueForKey:@"friends"] count];i++)
{
[friendsArrayFinal addObject:[[results valueForKey:@"friends"] objectAtIndex:i]];
}
}
Here you can get all the objects in FriendsArrayfinal. If you want to access specific object than use:
NSString *uid=[NSString stringWithFormat:@"%@",[[friendsArrayFinal objectAtIndex:0] valueForKey:@"uid"]];
Upvotes: 0
Reputation: 13600
you can access values like following
for(NSDictionary *item in friendsArrayFinal) {
NSLog(@"Item: %@", item);
NSLog(@"%@",[item valueForKey:@"uid"]);
NSLog(@"%@",[item valueForKey:@"fbUid"]);
NSLog(@"%@",[item valueForKey:@"name"]);
NSLog(@"%@",[item valueForKey:@"score"]);
}
Upvotes: 0