由於您沒有提供正確的JSON響應。我用了你上面的JSON建立在我的項目在本地一個,並用它解析
請找我在我的項目
使用Sample.json
{
"test": {
"Boots": [
"Brogue",
"Chelsea",
"Chukka",
"Dress",
"Rain/Snow",
"Rugged"
],
"Dress Shoes": [
"Oxfords",
"Formal Shoes"
],
"Loafers/Slip-ons": [
"Slip-ons",
"Loafers"
],
"Sandals": [
"Flip Flops",
"Slides"
],
"Sneakers": [
"Low Top",
"High Tops",
"Running Shoes",
"Slip-ons"
]
}
}
樣品JSON文件
我用下面的代碼來獲取數組值。有兩種方法來解析和獲取數組值。
方法1
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Sample" ofType:@"json"];
NSError * error;
NSString *fileContents = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
if(error)
{
NSLog(@"Error reading file: %@",error.localizedDescription);
}
NSDictionary *dataList = [NSJSONSerialization JSONObjectWithData:[fileContents dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:NULL];
NSLog(@"%@",dataList);
NSDictionary *sourceData = [dataList objectForKey:@"test"];
NSArray * boots = [sourceData objectForKey:@"Boots"];
NSArray * shoes = [sourceData objectForKey:@"Dress Shoes"];
NSArray * loafers = [sourceData objectForKey:@"Loafers/Slip-ons"];
NSArray * sandals = [sourceData objectForKey:@"Sandals"];
NSArray * sneakers = [sourceData objectForKey:@"Sneakers"];
NSLog(@"\n %@ \n %@ \n %@ \n %@ \n %@",boots,shoes,loafers,sandals,sneakers);
方法2
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Sample" ofType:@"json"];
NSError * error;
NSString *fileContents = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
if(error)
{
NSLog(@"Error reading file: %@",error.localizedDescription);
}
NSDictionary *dataList = [NSJSONSerialization JSONObjectWithData:[fileContents dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:NULL];
NSLog(@"%@",dataList);
NSDictionary *sourceData = [dataList objectForKey:@"test"];
NSArray *keyValues = [sourceData allKeys];
for (int i =0 ; i < keyValues.count; i++) {
NSArray *innerContents = [sourceData objectForKey:[keyValues objectAtIndex:i]];
NSLog(@"%@ \n", innerContents);
}
如果你希望能夠通過名稱來訪問他們,你最好能夠將其存儲在一個NSDictionary。如果沒有,那麼你會想要使用'NSArray.objectAtIndex' – brandonscript
我試過'objectAtIndex:indexPath.row'爲一個UITableView,它已經崩潰 –
@brandonscript你可能會誤解,我不想獲得什麼裏面「啓動「試圖獲得密鑰」啓動「它的自我 –