标签:
JSON解析步骤:
1.获取json文件路径
NSString*path = [[NSBundle mainBundle] pathForResource:@"Teacher"ofType:@"json"];
2.读取文件中的data
NSData *data = [NSData dataWithContentsOfFile:path];
3.把data转化为可变数组或者可变字典 是字典还是数组要看json最外层数据是什么.NSJSONSerialization是重点
NSError *error = nil; NSMutableArray*dataArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainerserror:&error];
- (void)parserDidStartDocument:(NSXMLParser *)parser { // 初始化数组 self.dataArray = [NSMutableArray array]; NSLog(@"已经开始分析文件"); } - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { // 初始化model if ([elementName isEqualToString:@"Student"]) { self.model = [[StudentModel alloc] init]; } NSLog(@"<%@>", elementName); // NSLog(@"开始遇到节点"); } - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { // 保存字符串 self.string = string; //NSLog(@"发现字符"); NSLog(@"%@", string); } - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { // 给model赋值 if ([elementName isEqualToString:@"name"]) { self.model.name = self.string; } else if ([elementName isEqualToString:@"gender"]) { self.model.gender = self.string; } else if ([elementName isEqualToString:@"age"]) { self.model.age = self.string; } else if ([elementName isEqualToString:@"motto"]) { self.model.motto = self.string; } else if ([elementName isEqual;ldghToString:@"Student"]) { // 节点名字等于Student的时候一个model就赋值完成了 可以装进数组中 [self.dataArray addObject:self.model]; [_model release]; } NSLog(@"遇到结束节点触发"); NSLog(@"</%@>", elementName); } - (void)parserDidEndDocument:(NSXMLParser *)parser { NSLog(@"%@", self.dataArray); NSLog(@"已经结束分析文件"); }现在一般多使用json解析.
标签:
原文地址:http://www.cnblogs.com/pp123/p/4820478.html