我正在努力寻找应该简单的事情。将以下JSON解析为tableview,将类别名称作为节标题以及搜索这些节的详细信息。这是我的JSON。如你所见,我有多个类别(例如婴儿和其他婴儿用品等),在这些类别下,我想要的每个类别的细节。
{
"items": {
"post": {
"categories": [
[
"Baby",
{
"title": "trying with category id again",
"price": "3344.55",
"category_key": "3"
}
],
[
"Cars & Trucks",
{
"title": "putting in title",
"price": "3000.99",
"category_key": "7",
}
],
[
"Cars & Trucks",
{
"title": "adding another listing",
"price": "400000.99",
"category_key": "7"
}
],
这是我的代码。总的来说,我有14个类别。我下面的代码似乎解析了JSON,它知道有14个类别,但值显示为0,1,2,3等(键)而不是category_name的实际值。
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
_tableData = [json objectForKey:@"items"][@"post"][@"category_name"];
_filteredItemArray = [_tableData valueForKey:@"category_name"];
dispatch_async(dispatch_get_main_queue(), ^{
[m_tableView reloadData];
});
//_buyCategory = json[@"items"][@"post"];
NSLog(@"Items in Dictionary: %@", _filteredItemArray); /// I CAN SEE ALL MY DATA
NSLog(@"Array Count: %u", [_filteredItemArray count]); ///THE COUNT SHOWS 14
}
这是我的表格数据:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [[_filteredItemArray objectAtIndex:section] objectForKey:@"category_name"]; ///APP CRASHES HERE...BUT THIS SEEMS RIGHT TO ME
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [[[[_tableData objectAtIndex:section] objectAtIndex:1] allKeys] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
CustomBuyMainCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSDictionary* tempResults = [_tableData objectAtIndex:indexPath.row];
_buyTitle = [tempResults objectForKey:@"title"];
_buyPrice = [tempResults objectForKey:@"price"];
cell.buyMainTitle.text = _buyTitle;
cell.buyMainPrice.text = _buyPrice;
//NSLog(@"TempResults: %@", _buyTitle);
return cell;
}
#pragma mark - Segue
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:@"showDetail"]) {
BuyDetail *buyDetail = [segue destinationViewController];
// In order to manipulate the destination view controller, another check on which table (search or normal) is displayed is needed
if(sender == self.searchDisplayController.searchResultsTableView) {
//buyDetail.itemDetailArray = [self.tableData objectAtIndex:[m_tableView indexPathForSelectedRow].row];
}
else {
//buyDetail.itemDetailArray = [self.tableData objectAtIndex:[m_tableView indexPathForSelectedRow].row];
}
}
}
我的PHP:
$channel ['json']['categories'][$category_name][]['items'][] = array(
'ID' => $ID,
'title' => $title,
'price' => $price,
'date_time' => $date_time,
'description' => $description,
);
}
$channels = array($channel);
$json = json_encode($channel);
header('Content-type: application/json');
echo $json;
我认为我遗漏了一些东西所以非常感谢任何帮助。
答案 0 :(得分:1)
在扩展讨论之后,您的JSON似乎已标准化,我们可以继续使用以下代码:
- (void)fetchedData:(NSData *)responseData
{
NSError *error;
//declare "NSDictionary *jsonDictionary;" in the .h of this class
//no need to make an array, simply use the response dictionary
jsonDictionary = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
//get all keys (since there may be "holes" in the numbering)
//declare "NSArray *arrAllKeys;" in the .h of this class
arrAllKeys = [[jsonDictionary objectForKey:@"items"] allKeys];
[m_tableView reloadData];
//NOTE: No need for _tableData or _filteredItemArray objects
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [[jsonDictionary objectForKey:@"items"] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[[[jsonDictionary objectForKey:@"items"]
objectForKey:[arrAllKeys objectAtIndex:section]]
objectForKey:@"details"] count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [[[jsonDictionary objectForKey:@"items"]
objectForKey:[arrAllKeys objectAtIndex:section]]
objectForKey:@"categories"];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
CustomBuyMainCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[NSBundle mainBundle] loadNibNamed:@"CustomBuyMainCell"
owner:self
options:nil]
objectAtIndex:0];
}
NSString *categoryItemName = [[[[[jsonDictionary objectForKey:@"items"]
objectForKey:[arrAllKeys objectAtIndex:indexPath.section]]
objectForKey:@"details"]
objectAtIndex:indexPath.row]
objectForKey:@"title"];
NSString *categoryItemPrice = [[[[[jsonDictionary objectForKey:@"items"]
objectForKey:[arrAllKeys objectAtIndex:indexPath.section]]
objectForKey:@"details"]
objectAtIndex:indexPath.row]
objectForKey:@"price"];
[cell.buyMainTitle setText:categoryItemName];
[cell.buyMainPrice setText:categoryItemPrice];
return cell;
//NOTE: No need for tempResults or _buyTitle or _buyPrice objects anymore
//(unless you are using _buyTitle & _buyPrice elsewhere as well)
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"showDetail"]) {
BuyDetail *buyDetail = [segue destinationViewController];
//declare and synthesize in the BuyDetail.h
//"@property (nonatomic, strong) NSDictionary *selectedCategoryItem;"
int mySelectedSection = [m_tableView indexPathForSelectedRow].section;
int mySelectedRowInSection = [m_tableView indexPathForSelectedRow].row;
buyDetail.selectedCategoryItem = [[[[jsonDictionary objectForKey:@"items"]
objectAtIndex:[arrAllKeys objectAtIndex:mySelectedSection]]
objectForKey:@"details"]
objectAtIndex:mySelectedRowInSection];
//NOTE: selectedCategoryItem is a dictionary object in your BuyDetail
//handle it like as you would handle any other dictionary
}
}
distance
值是整数,因此我们需要以这种方式获取它:
int distanceInMiles = [[[[[[[jsonDictionary objectForKey:@"items"]
objectForKey:[arrAllKeys objectAtIndex:indexPath.section]]
objectForKey:@"details"]
objectAtIndex:indexPath.row]
objectForKey:@"distance"]
objectForKey:@"miles"] intValue];
//assuming categoryItemDistance is NSString object
categoryItemDistance = [NSString stringWithFormat:@"%d",distanceInMiles];