I have the following json file and I am trying to parse it from my iOS app. I defined a method to parse the file but I don't know how to handle the integers, which are the IDs. I want to put the data in an array (promotions) which contains a title and an array of products (explained better below). Any suggestion or good reference?
Json file:
"promotions": {
"1": {
"title": "promotion title",
"product": {
"1": {
"title": "product title",
"description": "this is the description"
},
"2": {
"title": "product title",
"description": "this is the description"
}
}
},
"2": { "3": {
"title": "product title",
"description": "this is the description"
},
"4": {
"title": "product title",
"description": "this is the description"
}
}
}
}
These are my data classes:
Promotion { NSString *title; NSArray *products;}
Product { NSString *title; NSString *description;}
And my function to load the json and add all the objects in an array of promotions which contains, for each promotion, an array of products.
- (NSArray *) infoFromJSON{
NSURL *url=[NSURL URLWithString:urlJSON];
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:30.0];
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSMutableArray *promotions = [[NSMutableArray alloc] init];
NSArray *array = [jsonDictionary objectForKey:@"promotions"];
NSLog(@"array: %@", array);
NSLog(@"items en array %d", [array count]);
NSLog(@"object 1 en array: %@", [array objectAtIndex:1]);
// Iterate through the array of dictionaries
for(NSDictionary *dict in array) {
Promotion *promotion= [[Promotion alloc] initWithJSONDictionary:dict];
// Add the promotion object to the array
[promotions addObject:promotions];
//Add the products to each promotion??
}
// Return the array of promotion objects
return promotions;
}
{(and possibly the trailing}-- I haven't counted). Every character in a JSON file has meaning, and you must learn how to read them correctly.