Reputation: 97
How's it going folks---I'm having trouble iterating through an array in xcode--hoping someone can point me in the right direction..here's my response json response
NSString *str=@"jsonUrlremoved";
NSURL *url=[NSURL URLWithString:str];
NSData *data=[NSData dataWithContentsOfURL:url];
NSError *error=nil;
id response=[NSJSONSerialization JSONObjectWithData:data options:
NSJSONReadingMutableContainers error:&error];
{
"item":{
"1":{
"title":"Item Title",
"description":"long description",
"date":" March 01, 2014"
},
"2":{
"title":"Item Title",
"description":"long description",
"date":" March 01, 2014"
},
"3":{
"title":"Item Title",
"description":"long description",
"date":" March 01, 2014"
}
}
}
I've tried converting to nsdictionary as well as nsobject and nsarray with no luck (cause I'm a noob)
NSDictionary *results = [response objectForKey:@"item"];
for (NSDictionary *result in results) {
NSString *image = [result objectForKey:@"image"];
NSString *desc = [result objectForKey:@"description"];
NSString *title = [result objectForKey:@"title"];
}
The app either crashes or returns null---any guidance is appreciated
Upvotes: 1
Views: 93
Reputation: 2908
One way of doing this if you dont't want to restructure your JSON can be as follows, it's just a way around not to be prescribed :P
NSDictionary *results = [response objectForKey:@"item"];
NSString *image = [[result objectForKey:@"1"]objectForKey:@"image"] ;
NSString *desc = [[result objectForKey:@"1"]objectForKey:@"description"];
NSString *title = [[result objectForKey:@"1"]objectForKey:@"title"];
and similarly for the rest of the objects
Upvotes: 0
Reputation: 3012
Your JSON Object does not contain an array. So Iterating through it is out of question. You essentially have nested Dictionaries. If you need to do some Array stuff, I'd consider changing your JSON's Item object's value to an Array "[]" instead of a Dictionary "{}". That way, you don't even have to deal with indices in your JSON object. You get them for free.
The "Corrected" JSON object would look something like this:
{
"item":[
{
"title":"Item Title",
"description":"long description",
"date":" March 01, 2014"
},
{
"title":"Item Title",
"description":"long description",
"date":" March 01, 2014"
},
{
"title":"Item Title",
"description":"long description",
"date":" March 01, 2014"
}
]
}
Upvotes: 1
Reputation: 5935
For openers, your data doesn't have a value for the key @"image".
But beyond that, when you get the object for @"item", what it will return you is an array of three more dictionaries, with keys @"1", @"2", and @"3". Do a get on those keys, and you should then be able to get the subfields.
Do a 'po result' in the debugger when you breakpoint at the beginning of your 'for' loop. It will print out the type of the object you've got (whether it's an NSDictionary or NSArray) and change your code to agree to what's in your data structure.
Upvotes: 1