I'm retrieving data only once from the server as JSON on my TableView and it is working fine. I couldn't print a specific subject from the JSON.
For example according to my JSON I just want to print the name's of the Dining Room
or Coffees
without Bedroom
. How I can make that?
I can only print the whole name's of subcategory > products(names) with my code.
Code:
-(void)getJSON{
NSString *string = BaseURLString;
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
_dic = (NSDictionary *)responseObject;
for (NSDictionary *dict in [_dic objectForKey:@"categories"]) {
if ([[dict valueForKey:@"sub_category"] isKindOfClass:[NSArray class]])
{
[_arraySubCategory addObject:[[[dict valueForKey:@"sub_category"] valueForKey:@"products"] valueForKey:@"name"]];
}
}
My JSON Data:
Array
(
[categories] => Array
(
[0] => Array
(
[category_id] => 100
[name] => Shop By Room
[sub_category] => Array
(
[0] => Array
(
[category_id] => 72
[name] => BEDROOM
[sub_category] => 0
[product_total] => 11
[products] => Array
(
[0] => Array
(
[product_id] => 138
[name] => Jewellery Holder
)
[1] => Array
(
[product_id] => 139
[name] => Jewellery Holder
)
)
)
)
[1] => Array
(
[category_id] => 67
[name] => DINING ROOM
[sub_category] => 0
[product_total] => 73
[products] => Array
(
[0] => Array
(
[product_id] => 248
[name] => Amuse
)
[1] => Array
(
[product_id] => 239
[name] => Amuse
)
)
.
.
.
[1] => Array
(
[category_id] => 101
[name] => Drink
[sub_category] => Array
(
[0] => Array
(
[category_id] => 103
[name] => Coffees
[sub_category] => 0
[product_total] => 14
[products] => Array
(
[0] => Array
(
[product_id] => 229
[name] => Cafe1
)
[1] => Array
(
[product_id] => 233
[name] => Cafe2
)
I'm really not sure specifically what you're asking. It looks like you only want to print out the values from within Coffees
. Just skip categories and subcategories that don't match the criteria you want by using if (...) continue;
.
for (NSDictionary *dict in [_dic objectForKey:@"categories"]) {
if (![dict[@"name"] isEqualToString:@"Drink"]) continue;
for (NSDictionary *subcategory in [dict valueForKey:@"sub_category"])
{
if (![subcategory[@"name"] isEqualToString:@"Coffees"]) continue;
for (NSDictionary *product in subcategory[@"products"]) {
[_arraySubCategory addObject:product[@"name"]];
}
}
}
You should also be aware that what you have posted as JSON is not valid JSON. This appears to be a print_r
from PHP.