我正在使用URL访问JSON文件
我从以下代码
NSData* data=[jsonString dataUsingEncoding: [NSString defaultCStringEncoding] ];
NSError *error; //where jsonString is string of URL
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (jsonDictionary==nil) {
NSLog(@"Error::Loading");
}else
{
NSArray *array = [jsonDictionary objectForKey:@"categories"];
for (int i=0; i<[array count]; i++) {
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setValue:[[array objectAtIndex:i] valueForKey:@"cat_id"] forKey:@"cat_id"];
[dic setValue:[[array objectAtIndex:i] valueForKey:@"cat_name"] forKey:@"cat_name"];
[dic setValue:[[array objectAtIndex:i] valueForKey:@"cat_image"] forKey:@"cat_image"];
[dic setValue:[[array objectAtIndex:i] valueForKey:@"cat_list"] forKey:@"cat_list"];
[newsArray addObject:dic];
[categoryArry addObject:[dic valueForKey:@"cat_name"]];
[categoryId addObject:[dic valueForKey:@"cat_id"]];
[categoryImage addObject:[dic valueForKey:@"cat_image"]];
[categoryList addObject:[dic valueForKey:@"cat_list"]];
[dic release];
}
}
并获得json这样的结构
{
"categories": [
{
"cat_id": "15",
"cat_name": "Shop",
"cat_image": null,
"cat_list": [
{
"sub_cat_name": "New Arrivals",
"Cat_Data": [
{
"prod_name": "Generals Coat Biege",
"prod_price": "215.0000",
"prod_image": "honey_beau_lookbook_winter13_febmarch-24.jpg"
}
]
}
]
}
]
}
categoryArry仅包含ine值“Shop”
但我想访问categoryArry中的“sub_cat_name”并跳过商店等级....
简而言之,我想将“sub_cat_name”存储到categoryArry。
答案 0 :(得分:0)
我正在使用名为AFNetworking的第三方库来发出JSON请求并解析响应。
以下是一个例子:
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:@"http://yoursite.com"];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST"
path:@"blah/path"
parameters:@{@"jsonKey":@"jsonValue"}];
AFJSONRequestOperation *operation = [AFJSONRequestOperation
JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *res, id json) {
// Use the json here
json[@"categories"][0][@"cat_list"];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id json) {
//Handle Errors
}];
[operation start];
答案 1 :(得分:0)
在你的代码替换:
[categoryArry addObject:[dic valueForKey:@"cat_name"]];
通过
[categoryArry addObject:[[dic valueForKey:@"cat_list"][0]] valueForKey:@"sub_cat_name"];
无论如何,您可以直接使用jsonDictionary
,而不是创建另一个dict
。
答案 2 :(得分:0)
当然你只需要这样做:
NSArray *catlist = [dic valueForKey:@"cat_list"]
NSDictionary *firstcat = [catlist objectAtIndex:0];
NSString *subcatname = [firstcat valueForKey:@"sub_cat_name"];
当然,假设您在cat_list
数组中至少有一个项目。