I need to iterate the "c"id,"project" id,name in the following JSON response:
{
"a": {
"user": {
"id": 1,
"name": "b"
},
"startday": "2015-12-27",
"status": "New",
"total": 6,
"c": [
{
"id": 768,
"project": {
"id": 8,
"name": "d"
},
"user": {
"id": 1,
"name": "b"
},
"activity": {
"id": 8,
"name": "e"
},
"hours": 2,
"comments": "",
"spent_on": "2015-12-27"
},
{
"id": 775,
"project": {
"id": 8,
"name": "d"
},
"user": {
"id": 1,
"name": "b"
},
"activity": {
"id": 8,
"name": "e"
},
"hours": 4,
"comments": "",
"spent_on": "2015-12-28"
}
]
}
}
I've tried
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonSource options:NSJSONReadingMutableContainerserror:nil];
NSLog(@"%@",jsonObjects);
if ([jsonObjects objectForKey:@"a"] != [NSNull null]) {
NSArray *itemArray = [jsonObjects objectForKey:@"a"];
for (NSDictionary *itemDic in itemArray){
NSString * user;
NSArray *user_data =[itemDic valueForKey:@"c"];
user = [user_data valueForKey:@"id"];
NSLog(@"%@",user);
}
}
which throws the error
This class is not key value coding complaint for the key c.
Then I tried
NSDictionary *dictionary =[NSJSONSerializationJSONObjectWithData:jsonSource options:kNilOptions error:&error];
NSArray * time_entrid = [dictionary valueForKeyPath:@"a.c.id"];
NSLog(@"%@",time_entrid);
How can I solve the error I've mentioned above and iterate properly? Does using the second way enable me to iterate too?
You have One NSArray and NSDictionary For "a" NSDictionary use (you can't iterate NSDictionary only way is)
[[[dictionary objectForKey:@"a"] objectForKey:@"user"] objectForKey:@"id"]
you will get 1, change id by name you will get b
For NSArray
[[[[dictionary objectForKey:@"a"] objectForKey:@"c"] objectAtIndex:0] objectForKey:@"id"]
you will get id 768
For project id
[[[[[dictionary objectForKey:@"a"] objectForKey:@"c"] objectAtIndex:0] objectForKey:@"project"] objectForKey:@"id"]
you will get 8
[[[[[dictionary objectForKey:@"a"] objectForKey:@"c"] objectAtIndex:0] objectForKey:@"project"] objectForKey:@"name"]
you will get name
to iterate array use
for(int i=0; i<[[[dictionary objectForKey:@"a"] objectForKey:@"c"] count];i++)
{
NSLog(@"%@", [[[[dictionary objectForKey:@"a"] objectForKey:@"c"] objectAtIndex:i] objectForKey:@"id"]);
}