网络篇 - 04.网络数据解析(JSON)

这篇博客探讨了网络数据解析,重点关注JSON格式。介绍了JSON作为主流数据格式的特点,强调了其与Objective-C数据类型的对应关系。文章还讨论了在iOS中四种常见的JSON解析方案,特别是性能最佳的苹果原生NSJSONSerialization。最后,通过示例讲解了本地数据和网络数据的JSON解析,以及如何将OC对象转换为JSON数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.网络数据解析概述

  • 由于服务器端返回给我们的数据格式有多种,我们需要将数据转换为我们需要的格式,这里就需要用到数据解析
  • 服务器传输给我们的数据主要有三种:
    • JSON
    • XML
    • 二进制数据(图片、视频之类的信息)

2.JSON数据概述

  • JSON数据是民间版的数据格式,是目前最主流的数据格式,另一种是官方版的数据个数XML
  • JSON是一种轻量级的数据格式,一般用于数据交互
  • JSON的格式很像OC中的字典和数组
{"name" : "jack", "age" : 10}
{"names" : ["jack", "rose", "jim"]}
  • 标准JSON格式的注意点:key必须用双引号
  • 要想从JSON中挖掘出具体数据,得对JSON进行解析
  • 我们解析JSON数据就是将其转换为 OC数据类型
  • JSON和OC对象转换后对应数据类型
    • {} -> NSDictionary @{}
    • [] -> NSArray @[]
    • “jack” -> NSString @”jack”
    • 10 -> NSNumber @10
    • 10.5 -> NSNumber @10.5
    • true -> NSNumber @1
    • false -> NSNumber @0
    • null -> NSNull

3.JSON解析方案

  • 在iOS中,JSON的常见解析方案有4种
  • 在iOS中,JSON的常见解析方案有4种
    • 第三方框架:JSONKit、SBJson、TouchJSON(性能从左到右,越差)
    • 苹果原生(自带):NSJSONSerialization(性能最好)
  • 由于苹果自带的JSON解析性能最好,所以我们主要使用的也是苹果原生的解析器

4.JSON解析示例

  • 本地数据解析
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    NSString *json = @"[\"jack\",\"tom\"]";
    NSString *json1 = @"null";
    // 将字符串转换为二进制数据
    NSData *data = [json1 dataUsingEncoding:NSUTF8StringEncoding];
    // 解析JSON数据
    /* 参数解释:
     第一个参数:传入要解析的数据
     第二个参数:解析模式
     NSJSONReadingMutableContainers = 转换出来的对象是可变数组或者可变字典
     NSJSONReadingMutableLeaves = 转换出来的OC对象中的字符串是可变的,注意: iOS7之后无效 bug
     NSJSONReadingAllowFragments = 如果服务器返回的JSON数据, 不是标准的JSON, 那么就必须使用这个值, 否则无法解析
     */
    id objc = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    NSLog(@"%@",[objc class]);
    // 输出结果NSNull
}
  • 网络数据解析
// 解析网络数据
-(void)JSONNetworkData{
    // 1.获取网络数据
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=zj&pwd=123it&type=JSON"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        // 2.解析网络数据
        // 2.1打印数据,获取数据格式
        NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);// 输出结果:{"success":"登录成功"}
        // 2.2解析数据
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",dict);// 输出结果:{success = "\U767b\U5f55\U6210\U529f";}
    }];
}
  • OC对象转换为JSON数据
-(void)objc2JSON{
    NSDictionary *dict = @{
                           @"name":@"MrRight",
                           @"age":@"25",
                           @"sex":@"Man",
                           };
    /*
     第一个参数: 需要转换为JSON的对象
     第二个参数: 转换为JSON之后是否需要排版
     第三个参数: 错误信息
     */
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    // 将JSON数据转换为字符串
    NSString *temp = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@",temp);
    /* 输出结果:
     {
      "name" : "MrRight",
      "age" : "25",
      "sex" : "Man"
    }
    */
}

5.复杂JSON数据解析

  • 创建UITableViewController
  • 一般开发中,正常JSON数据的解析,我们都会创建模型来保存解析后的数据,这里由于获取的数据比较简单,就没有新建模型了
#import "ViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import <MJRefresh/MJRefresh.h>
#import <MediaPlayer/MPMoviePlayerViewController.h>

@interface ViewController ()
@property (nonatomic, strong) NSArray *videos;// 视频信息
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 1.获取网络数据
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/video?type=JSON"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        // 2.解析JSON数据
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        self.videos = dict[@"videos"];

        [self.tableView reloadData];
    }];
}

#pragma mark - UITableViewDataSource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.videos.count;   
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //    1.创建cell
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    //    2.设置cell的数据
    NSDictionary *dict = self.videos[indexPath.row];
    cell.textLabel.text = dict[@"name"];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",dict[@"length"]];
    //   2.1 缓存并下载图片
    NSString *urlStr =[NSString stringWithFormat:@"http://120.25.226.186:32812/%@", dict[@"image"]];
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    [cell.imageView sd_setImageWithURL:url placeholderImage:nil];

    //    3.返回cell
    return cell;
}

#pragma mark - UITableViewDelegate
// 选中某一行后播放视频
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    // 获取视频URL
    NSDictionary *dict = self.videos[indexPath.row];
    NSString *urlStr =[NSString stringWithFormat:@"http://120.25.226.186:32812/%@", dict[@"url"]];
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    // 加载视频播放控制器
    MPMoviePlayerViewController *vc = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
    // 显示控制器
    [self presentViewController:vc animated:YES completion:nil];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值