IOS 解析Json数据(NSJSONSerialization)

 

什么是JSON

JSON是一种轻量级的数据格式,一般用于数据交互

服务器返回给客户端的数据,一般都是JSON格式或者XML格式(文件下载除 外)

JSON的格式很像OC中的字典和数组 {"name" : "jack", "age" : 10}

{"names" : ["jack", "rose", "jim"]}

●  标准JSON格式的注意点:key必须用双引号
  • ●  要想从JSON中挖掘出具体数据,得对JSON进行解析

  • ●  JSON 转换为 OC数据类型

●  iOS中,JSON的常见解析方案有4
  • ●  第三方框架:JSONKitSBJsonTouchJSON(性能从左到右,越差)

  • ●  苹果原生(自带):NSJSONSerialization(性能最好)

  • ●  NSJSONSerialization的常见方法

  • ●  JSON数据 ! OC对象

  • + (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;

OC对象 ! JSON数据
+ (NSData *)dataWithJSONObject:(id)obj options:
(NSJSONWritingOptions)opt error:(NSError **)error;


三、JSON解析
1.利用NSJSONSerialization类解析
* JSON数据(NSData) --> Foundation-OC对象(NSDictionary、NSArray、NSString、NSNumber)
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;

2.JSON解析规律
* { } --> NSDictionary @{ }
* [ ] --> NSArray @[ ]
* " " --> NSString @" "
* 10 --> NSNumber @10
@interface HMViewController ()
@property (nonatomic, strong) NSArray *videos;
@end

@implementation HMViewController

- (void)viewDidLoad
{
    [super viewDidLoad];      
    // 去除分割线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [MBProgressHUD showMessage:@"正在加载视频信息...."];
//    NSXMLParser  XML 解析
// MediaPlayerAVFoundation
    
    // 访问服务器数据
    NSString *urlStr = @"http://192.168.1.200:8080/MJServer/video";
    
    // 发送请求
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // GET
    request.timeoutInterval = 10;
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        // 隐藏
        [MBProgressHUD hideHUD];
        
        if (data) {
            // 解析json数据
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSArray *array = dict[@"videos"];
            
            NSMutableArray *videos = [NSMutableArray array];
            for (NSDictionary *videoDict in array) {
                HMVideo *video = [HMVideo videoWithDict:videoDict];
                [videos addObject:video];
            }
            self.videos = videos;
            
            // 刷新表格
            [self.tableView reloadData];
        } else {
            [MBProgressHUD showError:@"网络繁忙!!!"];
        }
    }];
}


#pragma mark - 数据源
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.videos.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"video";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    
    HMVideo *video = self.videos[indexPath.row];
    cell.textLabel.text = video.name;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"时长:%d分钟", video.length];
    
    // video.image == resources/images/minion_01.png
    NSString *imageUrl = [NSString stringWithFormat:@"http://192.168.1.200:8080/MJServer/%@", video.image];
    [cell.imageView setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"placeholder"]];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

@end
原文地址:https://www.cnblogs.com/liuwj/p/6606000.html