【问题标题】:JSON parsing in iOS and storing the results into Array在 iOS 中解析 JSON 并将结果存储到 Array
【发布时间】:2014-08-01 06:59:22
【问题描述】:

我是 iOS 新手,所以请回答这个幼稚的问题。所以我正在尝试使用.net web 服务。我能够从 Web 服务获取响应,响应如下所示

<?xml version="1.0" encoding="utf-8"?><soap:Envelope     
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"    
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><getDoctorListResponse 
xmlns="http://tempuri.org/"><getDoctorListResult>
[
  {

    "Zone": "CENTRAL NORTH",
    "DoctorName": "Dr Ang Kiam Hwee",

  },
  {

    "Zone": "CENTRAL",
    "DoctorName": "Dr Lee Eng Seng",

  }
]
</getDoctorListResult>
</getDoctorListResponse>
</soap:Body>
</soap:Envelope>

通过下面的代码,我可以得到唯一的 json

 - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
     {
            if ([currentElement isEqualToString:@"getDoctorListResult"]) {

             NSDictionary *dc = (NSDictionary *) string;
             NSLog(@"Dictionary is = \n%@", dc);

             } 
     } 

看起来像json的变量dc等于

[
   {

    "Zone": "CENTRAL NORTH",
    "DoctorName": "Dr Ang Kiam Hwee",

  },
  {

    "Zone": "CENTRAL",
    "DoctorName": "Dr Lee Eng Seng",

  }
]

我检查了许多类似的问题,例如Xcode how to parse Json Objectsjson parsing+iphone 和其他类似问题,但无法解决我的问题。 如何获取 ZoneDoctorName 的值并将其存储在 Array 中,然后在 TableView 中显示?

【问题讨论】:

    标签: ios json


    【解决方案1】:

    您需要将&lt;getDoctorListResult&gt;元素的内容收集到一个实例变量中,因此将以下内容添加为私有类扩展

    @interface YourClass ()
    {
        NSMutableString *_doctorListResultContent;
    }
    

    然后使用 XML 解析器委托收集元素内容:

    - (void) parser:(NSXMLParser *)parser
    didStartElement:(NSString *)elementName
       namespaceURI:(NSString *)namespaceURI
      qualifiedName:(NSString *)qualifiedName
         attributes:(NSDictionary *)attributeDict
    {
        self.currentElement = elementName;
        if ([self.currentElement isEqualToString:@"getDoctorListResult"]) {
            _doctorListResultContent = [NSMutableString new];
        }
    }
    
    - (void) parser:(NSXMLParser *)parser
    foundCharacters:(NSString *)string
    {
        if ([self.currentElement isEqualToString:@"getDoctorListResult"]) {
            [_doctorListResultContent appendString:string];  
        }
    }
    

    最后在did end element委托方法中解析JSON:

    - (void)parser:(NSXMLParser *)parser
     didEndElement:(NSString *)elementName
      namespaceURI:(NSString *)namespaceURI
     qualifiedName:(NSString *)qName
    {
        if ([elementName isEqualToString:@"getDoctorListResult"]) {
            NSError *error = nil;
            NSData *jsonData = [_doctorListResultContent dataUsingEncoding:NSUTF8StringEncoding];
            id parsedJSON = [NSJSONSerialization JSONObjectWithData:jsonData
                                                            options:0
                                                              error:&error];
            if (parsedJSON) {
                NSAssert([parsedJSON isKindOfClass:[NSArray class]], @"Expected a JSON array");
                NSArray *array = (NSArray *)parsedJSON;
                for (NSDictionary *dict in array) {
                    NSString *zone = dict[@"Zone"];
                    NSString *doctorName = dict[@"DoctorName"];
    
                    // Store in array and then reload tableview (exercise to the reader)
                }
            } else {
                NSLog(@"Failed to parse JSON: %@", [error localizedDescription]);
            }
    
        }
    }
    

    【讨论】:

    • 谢谢。它正在工作。现在,如果我有大约 20 个详细信息,我想在 TableView 中显示它们。我该怎么做?
    • @Aniruddha 对不起,我不会为你做所有的工作。我似乎一无所获;甚至没有赞成票。祝你好运!
    • 我已经接受并投了赞成票。无论如何谢谢你。我对 iOS 很陌生。我自己试试看。
    • @Aniruddha 好的。您需要将区域/医生名称收集到字典数组(另一个实例变量)中,一旦解析了所有 XML,调用 [self.tableView reloadData] 并实现表视图数据源/委托方法以从该数组中获取行。 那里有很多示例来展示如何做到这一点。
    【解决方案2】:

    我建议将“dc”存储为属性并将其用作 UITableView 数据源。

    self.dataSourceDict = dc;
    

    获取给定单元格的值(在tableView:cellForRowAtIndexPath: 方法中):

    //deque cell before that
    NSDictionary* cellData = [self.dataSourceDict objectAtIndex:indexPath.row];
    //assuming cell is cutom class extending UITableViewCell
    cell.zone = cellData[@"Zone"];
    cell.doctorName = cellData[@"DoctorName"];
    

    【讨论】:

    • 感谢您的回复,首先我只想访问DoctorNameZone 值并将其存储在字符串变量或NSArray 中。你能帮我解决这个问题吗?
    • 你真的需要你拥有的结构——它们已经在一个数组和每个实例(行)的内部对象(NSDictionry)中。如果您打算将它们显示为 UITableView,这是存储它们的最佳方式
    • 如果我只想在表格中显示医生姓名,那么呢?如何访问每个 DoctorName 值?假设我想将 DoctorName 和 Zone 存储在单独的数组中。那么如何获得个人价值并将其放入数组中?
    • 如果我做类似 NSString * name = [dc objectForKey:@"DoctorName"] 的事情,那就是 [__NSCFString objectForKey:]: unrecognized selector sent to instance 0x9a13400
    • [[dc objectAtIndex:0] objectForKey:@"DoctorName"] - 你有 NSArray 和 NSDictionaries 里面
    【解决方案3】:

    for(dc 中的 id 键)

    {

    NSString *doctorName = [key objectForKey:@"DoctorName"];
    
    NSString *zone = [key objectForKey:@"Zone"];
    }
    

    创建一个模型文件并使用该模型文件将这些值存储到数组中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-06
      • 2016-09-23
      • 2013-05-22
      • 1970-01-01
      • 2020-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多