23>IOS数据解析---------之JSON和XML解析

来源:互联网 发布:淘宝代销货 编辑:程序博客网 时间:2024/05/19 13:09

1.JSON解析

在ios中,json解析方案有4种,其中三种需要使用第三方框架:JSONKit、SBJson、TouchJSON (性能从左到右,越差)

苹果原生自带:NSJSONSerialization ,性能最好。

下面是利用NSJSONSerialization解析json数据的代码:
#import "TableVideosController.h"
#import "MBProgressHUD+MJ.h"
#import "ZQVideo.h"
#import "UIImageView+WebCache.h"
#import <MediaPlayer/MediaPlayer.h>

#define ZQUrl(path) [NSURL URLWithString:[NSString stringWithFormat:@"http://localhost:8080/MJServer/%@",path]]

@interface TableVideosController ()
@property (nonatomic,strong) NSMutableArray *videos;
@end

@implementation TableVideosController

- (NSMutableArray *)videos
{
    if(_videos == nil){
        self.videos = [NSMutableArray array];
    }
    return  _videos;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    NSURL *url = ZQUrl(@"video");
    NSURLRequest *request = [NSURLRequest  requestWithURL:url];
    // 发送异步请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if(connectionError || data == nil){
            [MBProgressHUD showError:@"网络繁忙,请稍后再试。"];
            return ;
        }
        
        // 解析JSON数据
       NSDictionary *dict =  [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSArray *videosArray = dict[@"videos"];
        for (NSDictionary *dict in videosArray) {
            ZQVideo *video = [ZQVideo initWithDict:dict];
            [self.videos addObject:video];
        }
        //刷新表格
        [self.tableView reloadData];
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return self.videos.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    ZQVideo *video = self.videos[indexPath.row];
    cell.textLabel.text = video.name;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"时长:%d分钟",video.length];
     NSURL *url = ZQUrl(video.image);
    
    [cell.imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeHolder"]];
    
    return cell;
}

#pragma mark - 代理方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 播放视频
    
    // 取出对应的视频模型
    ZQVideo *video = self.videos[indexPath.row];
    
    NSURL *url = ZQUrl(video.url);
    // 创建系统自带的视频播放器
    MPMoviePlayerViewController *playerVC = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
    // 显示播放器
    [self presentViewController:playerVC animated:YES completion:nil];

}
@end


2. XML解析

在IOS中,解析xml的手段有很多:

苹果原生:NSXMLPaser: sax解析方式,使用简单。

第三方框架:

libxml2: 纯C语言,默认包含在ios SDK中,同时支持DOM和SAX方式解析

GDataXML: DOM方式解析,由google开发,基于libxml2


xml的解析方式选择:

大文件:NSXMLParser、libxml2

小文件:GDataXML


GDataXML配置与解析:

1) 导入libxml2库

2) 设置libxml2的头文件搜索路径,在Head Search Path中加入/usr/include/libxml2

3)   设置链接参数(自动链接libxml2库),在Other Linker Flags中加入-lxml2

4)   由于GDataXML是非ARC的,因此得设置编译参数,应该在Build Phases->Compile Sources 中选中一个文件

,输入 -fno-objc-arc

下面是利用GData解析xml的代码:

 // 解析XML
        
        // 加载整个xml数据
        GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:data options:0 error:nil];
        // 获得根元素
        GDataXMLElement *root = doc.rootElement;
        // 获得根元素里面的所有video元素
        NSArray *element = [root elementsForName:@"video"];
        // 遍历所有的video元素
        for (GDataXMLElement *videoElement in element) {
            HMVideo *video  = [[HMVideo alloc] init];
            // 取出元素的属性
            video.id = [videoElement attributeForName:@"id"].stringValue.intValue;
            video.length = [videoElement attributeForName:@"length"].stringValue.intValue;
            video.name = [videoElement attributeForName:@"name"].stringValue;
            video.image = [videoElement attributeForName:@"image"].stringValue;
            video.url = [videoElement attributeForName:@"url"].stringValue;
            [self.videos addObject:video];
        }


2) 利用NSXMLParser解析数据

利用代理,实现NSXMLParserDelegate方法。然后在该代理方法中做处理。

代码:

 // 3.发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError || data == nil) {
            [MBProgressHUD showError:@"网络繁忙,请稍后再试!"];
            return;
        }
        
       // 解析xml数据,利用NSXMLParser
        NSXMLParser *parser = [[NSXMLParser alloc]  initWithData:data];
        parser.delegate = self;
        
        // 开始解析数据
        [parser parse];    
        // 刷新表格
        [self.tableView reloadData];
    }];


0 0