0

iOS 新手。我正在使用 AFNetworking 下载 JSON 数据并将数据放入 Dictionary 对象中。这是在以下代码中完成的:

-(void)locationRequest
{
NSURL *url = [NSURL URLWithString:@"http://sitespec/php/getlocations.php"];

NSURLRequest *request = [NSURLRequest requestWithURL:url];
//AFNetworking asynchronous url request
AFJSONRequestOperation *operation = [AFJSONRequestOperation
                                     JSONRequestOperationWithRequest:request
                                     success:^(NSURLRequest *request, NSHTTPURLResponse         *response, id responseObject)
                                     {

                                         self.locationsFromJSON = (NSDictionary *)responseObject;

                                         NSLog(@"JSON RESULT %@", responseObject);
                                         NSLog(@"JSON DICTIONARY %@", _locationsFromJSON);
                                         [self.tableView reloadData];
                                     }
                                     failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id responseObject)
                                     {
                                         NSLog(@"Request Failed: %@, %@", error, error.userInfo);
                                     }];

[operation start];

}

我正在获取数据并填充 Dictionary 数组,如下面的 NSLOG 调用的结果所示:

2013-05-12 12:44:08.851 sitespec[2024:c07] JSON RESULT (
    {
    city = "Rocky Mount";
    id = 1;
    name = "Rocky Mount";
    phone = "(252) 451-1811";
    state = NC;
    "street_address" = "620 Health Drive";
    zip = 27804;
},
    {
    city = "Elizabeth City";
    id = 2;
    name = "Elizabeth City";
    phone = "(252) 335-4355";
    state = NC;
    "street_address" = "109 Corporate Drive";
    zip = 27906;
}
)
2013-05-12 12:44:08.852 sitespec[2024:c07] JSON DICTIONARY (
    {
    city = "Rocky Mount";
    id = 1;
    name = "Rocky Mount";
    phone = "(252) 451-1811";
    state = NC;
    "street_address" = "620 Health Drive";
    zip = 27804;
},
    {
    city = "Elizabeth City";
    id = 2;
    name = "Elizabeth City";
    phone = "(252) 335-4355";
    state = NC;
    "street_address" = "109 Corporate Drive";
    zip = 27906;
}
)

但是,这就是我迷路的地方......

如何在我的 Dictionary 对象中访问这些数据

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

方法?

就像是:

 static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

cell.textLabel.text = [self.locationsFromJSON objectForKey:@"name"]; 

???

这不起作用,我收到 SIGBART 错误。我只是不知道如何读取数据并填充表格视图?

我该怎么做呢?任何帮助是极大的赞赏.....

4

3 回答 3

1

我经常看到这种情况,但我不明白为什么人们很难从字典中提取数据并用字典的内容填充表格视图。我不明白为什么人们不为 JSON 响应创建模型类,然后根据需要将模型添加到数组中。

因此,Tommy我强烈建议您创建一个名为 Address 的类模型(例如)并将所有 JSON 属性作为属性添加到您的模型类中,当您解析 JSON 时,您将创建 Address 类实例并将其添加到数组中。之后,在您的表格视图类中,您将拥有一个地址数组,用于:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section你会回来的yourAddressesArray.count

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {    Address *address = [yourAddressesArray objectAtIndex:indexPath.row];    //assign your address properties to labels etc 

}

当你有模型类时会更容易;)

编辑解析

从我在您的问题中看到的,您有一系列字典。所以我建议做这样的事情:

在您的 Address 类中,使用 josn 创建一个 imit 方法:

-(id)initAddressWithJSON:(id)JSON {
    slef = [super init];
    if(self) {
      self.city = [JSON objectForKey:@"city"];
      // set all the properties here
    }
    return self;
}

当您收到调用的 json 响应时,假设“jsonResopnse”您应该执行以下操作:

-(NSArray*)myAddressesFromJSON:(id)JSON {

   //you should add a validation here for JSON  (not null not empty)
   NSMutableArray *addresses = [[NSMutableArray alloc] init];
   Address *address;
   for(NSDictionary *addressDict in JSON) {
       address = [[Address alloc] initWithJSON:addressDict];
       [addresses addObject:address]; 
   }
   return addresses;
}

请注意,我是从头开始编写代码的,我没有使用 Xcode :) 并且可能存在一些构建错误(拼写错误),但我希望您明白这一点。另外我想你正在使用 JSONKit。

于 2013-05-12T17:41:51.073 回答
0

如我所见,您使用 JSON 请求并且UITableView在同一个类中。在方法中设置断点cellForRowAtIndexPath并检查是否已有数据。如果没有,那么:

如果您的字典已经填满,请在方法中询问- (NSInteger)numberOfRowsInSection:(NSInteger)section或已经在。numberOfSections否则返回 0。

在您接收 JSON 数据的方法中调用[tableView reloadData];

如果这不是问题,请告诉您在哪里得到 SIGBART 错误;)

于 2013-05-12T17:41:17.357 回答
-1

感谢 danypata 的出色反馈。我采取了稍微不同的路线来实现这一目标。让我想到的是 danypata 的评论“看起来你的 JSON 响应中有一个字典数组”......在 AFNetworking 块中,如果我得到 JSON 响应,我将 JSON 对象分配给定义为属性的数组当前的表视图控制器。

-(void)locationRequest

{ NSURL *url = [NSURL URLWithString:@"myurl"];

NSURLRequest *request = [NSURLRequest requestWithURL:url];
//AFNetworking asynchronous url request
AFJSONRequestOperation *operation = [AFJSONRequestOperation
                                     JSONRequestOperationWithRequest:request
                                     success:^(NSURLRequest *request, NSHTTPURLResponse *response, id responseObject)
                                     {

                                         self.locationsFromJSON = responseObject;
                                         [self.tableView reloadData];
                                     }
                                     failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id responseObject)
                                     {
                                         NSLog(@"Request Failed: %@, %@", error, error.userInfo);
                                     }];

[operation start];

}

我还在 JSON 响应中为每个值声明了一个 Mutable Dictionary 属性和一个 NSString 属性。在下面的 TableVIewCell 方法中,我抓取位于 index.row 的字典对象,并读出键的值并将它们分配给原型单元格标签属性。

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"locCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];    
if (cell == nil) {

    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle  reuseIdentifier:CellIdentifier];

}


self.dictObj = [[NSMutableDictionary alloc] init];
self.dictObj = [_locationsFromJSON objectAtIndex:indexPath.row];
cell.textLabel.text =  [_dictObj valueForKey:@"city"];  
cell.detailTextLabel.text = [_dictObj valueForKey:@"phone"];     
return cell;
}

这行得通!只是别人指出了明显的“看起来你有一个字典对象数组......”

于 2013-05-14T12:28:56.250 回答