我在 iOS 中初出茅庐,所以请回答这个幼稚的问题。所以我正在尝试使用.net 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);
}
}
变量
dc
看起来像 json
等于[
{
"Zone": "CENTRAL NORTH",
"DoctorName": "Dr Ang Kiam Hwee",
},
{
"Zone": "CENTRAL",
"DoctorName": "Dr Lee Eng Seng",
}
]
我检查了许多类似的问题,例如 Xcode how to parse Json Objects , json parsing+iphone和其他类似的问题,但无法解决我的问题。
如何获得
Zone
的值和 DoctorName
并将其存储在 Array 中,然后在 TableView 中显示?
最佳答案
您需要收集<getDoctorListResult>
的内容元素到实例变量中,因此将以下内容添加为私有(private)类扩展
@interface YourClass ()
{
NSMutableString *_doctorListResultContent;
}
然后使用 XML 解析器委托(delegate)收集元素内容:
- (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 结束元素委托(delegate)方法中解析 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]);
}
}
}
关于ios - 在 iOS 中解析 JSON 并将结果存储到 Array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25074594/