【问题标题】:How to parse this json in uitableview? [closed]如何在uitableview中解析这个json? [关闭]
【发布时间】:2013-05-24 05:09:41
【问题描述】:

我是iOS 的新手。我想在我的UITableView 中解析json,但我不知道该怎么做。我知道json 使用NSURL 解析,但是在这个直接json 解析中我遇到了问题。请帮助.. 在这里:

NSString *url = @"{\"LinkResult\":{\"0\":{\"Name\":\"Veeva - Devon1\",\"ButtonDisplay\":\"Veeva\",\"PasswordSaving\":\"Yes\",\"Status\":\"Success\",\"Message\":\"No Error\", \"Identifiers\": {\"Identifier1Name\": \"Identifier1value\",\"Identifier2Name\": \"Identifier2value\",\"Identifier3Name\": \"Identifier3value\"},}}}";

请告诉我接下来的步骤...

【问题讨论】:

  • 是响应还是发送postData
  • @Hercules 它是一个简单的 json,我想在我的 uitableview 中检索。我只是将这个 json 放在我的视图控制器中,所以我该如何进一步进行..请告诉...
  • 好的,我在看……等等
  • 是的.. 但我没有从任何 url 获取这个 json.. 它的静态写在我的代码中......
  • 你想在tableView中显示哪些信息?

标签: iphone ios objective-c json


【解决方案1】:

这是你的 JSON 的结构

{
    "LinkResult": {
        "0": {
            "Name": "Veeva - Devon1",
            "ButtonDisplay": "Veeva",
            "PasswordSaving": "Yes",
            "Status": "Success",
            "Message": "No Error",
            "Identifiers": {
                "Identifier1Name": "Identifier1value",
                "Identifier2Name": "Identifier2value",
                "Identifier3Name": "Identifier3value"
            }
        }
    }
}

使用任何在线生成器创建一个 json 文件并将其添加到您的项目中。有一个保存数据源的属性。

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"Data"
                                                        ofType:@"json"];
    NSData *data = [[NSData alloc]initWithContentsOfFile:filePath];

    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data
                                                         options:0
                                                           error:nil];

    //A dictionary which will contain info all users
    self.users = dict[@"LinkResult"];

}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[self.users allKeys] count];;
}

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

    // Configure the cell...

    NSArray *sortedKeys = [[self.users allKeys]sortedArrayUsingSelector:@selector(compare:)];
    NSString *key = sortedKeys[indexPath.row];

    NSDictionary *user = self.users[key]; 

    cell.textLabel.text = user[@"Name"];
    cell.detailTextLabel.text = user[@"Status"];

    return cell;
}

Source Code

【讨论】:

  • 非常感谢 Anup.. 如果我想检索单独单元格中的所有值,还能做什么??
  • @Deep 欢迎您,使用源代码您可以找出其余部分。一种方法是制作一个自定义 tableViewCell 以您想要的方式表示数据。
【解决方案2】:

您可能希望为此使用 NSJSONSerialization 类,例如:

NSData *json = [url dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
NSDictionary *identifiers = [dataDictionary objectForKey:@"Identifiers"];
// Do stuff with the data

希望这是有道理的。您可以使用以下方法从 JSON 字符串中提取元素:

[dataDictionary objectForKey:@"ElementName"];

【讨论】:

    【解决方案3】:

    要解析你可以像这样使用 nsdictionary...

    NSData *json = [url dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
        NSDictionary *identifiers = [dataDictionary objectForKey:@"Your key"];
    

    并在表格视图中显示它,您可以使用

    arr = [[JSONObject objectForKey:@“results”] objectForKey:@“Your key”];
    
    // and set cell text label as -
    
    cell.textLabel.text =[[arr objectAtIndex:indexPath.row] objectForKey:@"Your key"];
    

    【讨论】:

      【解决方案4】:

      您需要将您的json字符串转换为NSDictionary对象才能在tableView中使用,下面的代码会将其转换为NSDictionary对象,然后您可以使用其键值相应地设置值。

      - (void)viewDidLoad
      {
          NSString *jsonString = @"{\"LinkResult\":{\"0\":{\"Name\":\"Veeva - Devon1\",\"ButtonDisplay\":\"Veeva\",\"PasswordSaving\":\"Yes\",\"Status\":\"Success\",\"Message\":\"No Error\", \"Identifiers\": {\"Identifier1Name\": \"Identifier1value\",\"Identifier2Name\": \"Identifier2value\",\"Identifier3Name\": \"Identifier3value\"},}}}";
      
          NSData *jsondata=[jsonString dataUsingEncoding:NSUTF8StringEncoding];
          NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsondata options:0 error:nil];
      
          displaydata=[[dataDictionary valueForKey:@"LinkResult"] valueForKey:@"0"];
          NSMutableArray *mutableKeys=[[NSMutableArray alloc] initWithArray:[displaydata allKeys]];
          [mutableKeys removeObject:@"Identifiers"];
          keys=[[NSArray alloc] initWithArray:mutableKeys];
      
          NSLog(@"JSON DIct: %@", displaydata);
          [super viewDidLoad];
          // Do any additional setup after loading the view, typically from a nib.
      }
      
      
      - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
      {
          return [keys count];
      }
      
      
      - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
      {
          static NSString *cellIdentifier=@"cellIdentifier";
      
          UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
      
          if (cell==nil) {
              cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
          }
      
          cell.textLabel.text = [displaydata valueForKey:[keys objectAtIndex:indexPath.row]];
          return cell;
      }
      

      【讨论】:

      • 谢谢.. 但是如何在我的 tableviewcell 上显示这个 json 数据??
      • @Deep 你必须在 UITableViewController 的 cellForRowAtIndexPath 方法中这样做
      • @Deep 你可以用我的代码轻松替换你的代码。
      【解决方案5】:
          NSString *url = @"{\"LinkResult\":{\"0\":{\"Name\":\"Veeva - Devon1\",\"ButtonDisplay\":\"Veeva\",\"PasswordSaving\":\"Yes\",\"Status\":\"Success\",\"Message\":\"No Error\", \"Identifiers\": {\"Identifier1Name\": \"Identifier1value\",\"Identifier2Name\": \"Identifier2value\",\"Identifier3Name\": \"Identifier3value\"},}}}";
      
          NSData* jsonData = [url dataUsingEncoding:NSUTF8StringEncoding];
      
          NSError *error;
          NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
          NSLog(@"json is %@", json);
      
          NSDictionary *LinkResult = [json valueForKey:@"LinkResult"];
          NSLog(@"LinkResult is %@", LinkResult);
      
          for (id key in [LinkResult allKeys]) {
              NSLog(@"Value for 0 index is %@", [LinkResult valueForKey:key]);
      
              NSLog(@"ButtonDisplay is %@", [[LinkResult valueForKey:key] valueForKey:@"ButtonDisplay"]);
              NSLog(@"Message is %@", [[LinkResult valueForKey:key] valueForKey:@"Message"]);
              NSLog(@"Name is %@", [[LinkResult valueForKey:key] valueForKey:@"Name"]);
              NSLog(@"PasswordSaving is %@", [[LinkResult valueForKey:key] valueForKey:@"PasswordSaving"]);
              NSLog(@"Status is %@", [[LinkResult valueForKey:key] valueForKey:@"Status"]);
          }
      

      【讨论】:

        【解决方案6】:

        朋友来了

        NSString *url = @"{\"LinkResult\":{\"0\":{\"Name\":\"Veeva - Devon1\",\"ButtonDisplay\":\"Veeva\",\"PasswordSaving\":\"Yes\",\"Status\":\"Success\",\"Message\":\"No Error\", \"Identifiers\": {\"Identifier1Name\": \"Identifier1value\",\"Identifier2Name\": \"Identifier2value\",\"Identifier3Name\": \"Identifier3value\"},}}}";
        
        NSArray *arrComponents = [url componentsSeparatedByString:@","];
        NSMutableArray *arrmFilter = [[NSMutableArray alloc] init];
        
        for(int i = 0; i < [arrComponents count] ;i++)
        {
            NSString *str = [arrComponents objectAtIndex:i];
            //str = [str stringByReplacingOccurrencesOfString:@":" withString:@""];
            str = [str stringByReplacingOccurrencesOfString:@"\"" withString:@""];
            str = [str stringByReplacingOccurrencesOfString:@"{" withString:@""];
            str = [str stringByReplacingOccurrencesOfString:@"}" withString:@""];
            str = [str stringByReplacingOccurrencesOfString:@"0" withString:@""];
        
            [arrmFilter addObject:str];
        }
        
        NSLog(@"Filtered array = %@", arrmFilter);
        

        您必须对 `stringByReplacingOccurencesOfString 进行一些更改
        但是这个vill提取JSON.... 希望这会有所帮助..

        【讨论】:

        • 为什么是负分先生?插入数组后在DEMO代码中打印出来,您可以轻松地将数据放入TABLEVIEW
        • 你应该阅读 JSON 和 NSJSONSerialization 类
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-06-09
        • 2012-05-01
        • 2021-06-13
        • 2022-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多