【问题标题】:UITableView sections from JSON data来自 JSON 数据的 UITableView 部分
【发布时间】:2011-12-14 16:10:30
【问题描述】:

我有这样的 JSON 数据:

[{"id":"3","name":"jason"},{"id":"4","name":"karen"}]

我想为每对 [id, name] 构建一个包含一个部分的表格视图。部分标题应该是 id 值,每个部分的唯一单元格应该是 name 值。

如何将 JSON 数据解析为数组并使用 [array count] 来确定必须显示多少个部分?

非常感谢..

原谅我的英语不好!

【问题讨论】:

  • 感谢 Mr.Wizard 的编辑!

标签: iphone json uitableview


【解决方案1】:

实现UITableViewDatasource以下方法:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [JSONArray count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    return 1;
}

设置部分的标题值:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [[JSONArray objectAtIndex:section] objectForKey:@"id"];
}

要设置单元格的值,请实现UITableViewDelegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
        cell.textLabel.text = [[JSONArray objectAtIndex:indexPath.section] objectForKey:@"name"]; // set the cell's text here
    }
    return cell;
}

参考检查UITableViewDataSourceUITableViewDelegate

【讨论】:

    【解决方案2】:

    看看这个项目。它是一个使用 JSON 的框架: https://github.com/stig/json-framework/

    可以在以下位置找到此框架的教程: http://iosdevelopertips.com/networking/iphone-json-flickr-tutorial-part-1.html

    框架为 NSString 添加了一个类别。使用该类别,您可以将 JSON 数据解析为 NSArray(以您的示例为例的对象列表)或 NSDictionary(某些对象或结构):

    #import "JSON.h"
    ...
    NSString jsonString = //get your JSON from somewhere
    NSArray * array = [jsonString JSONValue];
    

    我希望我能给你一个印象,怎样做才能实现你的目标。更多信息在 JSON 项目的教程或提到的教程中。

    如何从您的 JSON 数组构建表在答案中:UITableView sections from JSON data

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多