如何在 UITableView 中显示 JSON 数据

Posted

技术标签:

【中文标题】如何在 UITableView 中显示 JSON 数据【英文标题】:How to display JSON Data in UITableView 【发布时间】:2012-06-04 02:36:41 【问题描述】:

我有以下 JSON 数据,这是来自我的 Web 服务的响应。

     "d": ["raumKlassenObject":"Telepresenzraum",
"raumKlassenObject":"Besprechungsraum",
"raumKlassenObject":"Videokonferenzraum",
"raumKlassenObject":"IT-Schulungsraum",
"raumKlassenObject":"Konferenzraum"]

如何在 TableView 中显示 Data Telepresenzraum、Besprechungsraum 等。

到目前为止,这是我的代码。

    - (void)viewDidLoad

    [super viewDidLoad];

    dic = [NSJSONSerialization JSONObjectWithData:result options:kNilOptions error:nil];
    array = [dic allKeys];



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView


    // Return the number of sections.
    return 1;


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section


    // Return the number of rows in the section.
    return array.count;


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

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

   cell.textLabel.text=[NSString stringWithFormat:@"%@",[dic objectForKey:@"d"]];    



return cell;

如果我这样做,Tableview 中的输出是

 ["raumKlassenObject":"Telepresenzraum","raumKlassenObject":"Besprechungsraum","raumKlassenObject":"Videokonferenzraum","raumKlassenObject":"IT-Schulungsraum","raumKlassenObject":"Konferenzraum"]

我不知道如何在 tableview 行中仅显示 Telepresenzraum、Besprechungsraum、Videokonferenzraum 等。

谢谢帮助。

【问题讨论】:

【参考方案1】:

您的***字典只有一个键“d”,因此 array.count 将为 1,而 [dic objectForKey:@"d"] 将是整个字典数组。

所以,修复这个重新定义数组为:

array = [[dic valueForKey:@"d"] valueForKey:@"raumKlassenObject"];

这应该为您提供该键的所有值的数组。然后,将下面的第一行替换为第二行:

cell.textLabel.text= [NSString stringWithFormat:@"%@",[dic objectForKey:@"d"]]; 
cell.textLabel.text= [array objectAtIndex:indexPath.row];

【讨论】:

【参考方案2】:

您需要对cell 进行零检查。在您滚动一点之前,它为零。如果为 nil,则需要使用 UITableView 单元格类的 init 方法实际创建单元格。

【讨论】:

我现在这样做了,但这并不能解决我的问题/问题 cell.textLabel.text=[dic objectForKey:[array objectAtIndex:indexPath.row]]; 它仍然是相同的输出 ["raumKlassenObject":"Telepresenzraum","raumKlassenObject":"Besprechungsraum","raumKlassenObject":"Videokonferenzraum","raumKlassenObject":" IT-Schulungsraum","raumKlassenObject":"Konferenzraum"]. 这是您字典中唯一的条目。您拥有的是一组字典,每个字典只有一个条目。所以实际上你需要的是...[[[dic objectForKey@"d"] objectAtIndex:indexPath.row] objectForKey@"raumKlassenObject"];. 我尝试了你的解决方案,但我得到一个错误 [__NSCFString objectAtIndex:]: unrecognized selector sent to instance

以上是关于如何在 UITableView 中显示 JSON 数据的主要内容,如果未能解决你的问题,请参考以下文章