Reputation: 175
How can I loop through this part of the json [{first set of values},{data->children->data->body}
in objective c?
Json is
[
{
"kind": "Listing"
},
{
"kind": "Listing",
"data": {
"children": [
{
"data": {
"body": "body1"
}
},
{
"data": {
"body": "body2"
}
}
]
}
}
]
My current code is
m_ArrList=[[NSMutableArray alloc]init];
NSDictionary *infomation = [self dictionaryWithContentsOfJSONString:@"surveyquestion.json"];
NSArray *array=[infomation objectForKey:@"data"];
int ndx;
NSLog(@"%@",array);
for (ndx = 0; ndx < [array count]; ndx++) {
NSDictionary *stream = (NSDictionary *)[array objectAtIndex:ndx];
NSArray *string=[stream valueForKey:@"children"];
//i am stuck here
}
What do I do at the "//i am stuck here" ?
Upvotes: 1
Views: 403
Reputation: 9836
Using NSJSONSerialization
try to implement this. Here you need to pass NSString
as jsonStr which you need to read from your file.
NSError *jsonError = nil;
id allValues = [NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]
options:0
error:&jsonError];
if(jsonError!=nil)
NSLog(@"Json_Err: %@",jsonError);
NSArray *array=allValues;
for (int ndx = 0; ndx < [array count]; ndx++) {
NSDictionary *stream = (NSDictionary *)[array objectAtIndex:ndx];
NSLog(@"%@",[stream objectForKey:@"kind"]);
NSArray *child = [[stream objectForKey:@"data"] objectForKey:@"children"];
//i am stuck here
for(int i =0; i <[child count];i++)
{
NSDictionary *childData = (NSDictionary *)[child objectAtIndex:i];
//NSLog(@"%@",[childData objectForKey:@"data"]);
NSLog(@"%@",[[childData objectForKey:@"data"] objectForKey:@"body"]);
}
}
Upvotes: 0
Reputation: 13600
// You Just need to Implement following Lines and you will get all the data for Key Body in children array
NSDictionary *infomation = [self dictionaryWithContentsOfJSONString:@"surveyquestion.json"];
NSArray *string= [[infomation objectForKey:@"data"] objectForKey:@"children"];
[string enumerateObjectsUsingBlock:^(id obj, NSUInteger ind, BOOL *stop){
NSLog(@"Body : %@",[[obj objectForKey:@"data"] objectForKey:@"body"]);
}];
Upvotes: 0
Reputation: 12671
You might need to add the values of @"children"
dictionary in an array and then parse that array to get the data inside children
[childrenArray addObject:[stream objectForKey:@"children"]];
// finally parse childrenArray
Upvotes: 1