• iOS json数据的解析


    作为一种轻量级的数据交换格式,json正在逐步取代xml,成为网络数据的通用格式。

    有的json代码格式比较混乱,可以使用此“http://www.bejson.com/”网站来进行JSON格式化校验(点击打开链接)。此网站不仅可以检测Json代码中的错误,而且可以以视图形式显示json中的数据内容,很是方便。

    下面介绍一种系统自带的解析方法:

     1 //1.获取文件访问的路径
     2      NSString *path=@"http://1.studyios.sinaapp.com/getAllClass.php";
     3     //2.将文件路径封装成 URL 即 网址
     4     NSURL *url=[NSURL URLWithString:path];
     5     //3.将请求的数据解析成data类型的对象
     6     NSData *data=[NSData dataWithContentsOfURL:url];
     7     NSLog(@"%@",data);
     8     __autoreleasing NSError *error;
     9     //4.json数据解析
    10     NSArray *arrjson=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
    11     NSLog(@"%@",arrjson);
    12     for (NSDictionary *dic in arrjson) {
    13         NSLog(@"%@,%@,%@",dic[@"cid"],dic[@"cname"],dic[@"cpwd"]);
    14     }

     在介绍另一种方法:

     1 //1.获取文件访问的路径
     2     NSString *path=@"http://1.studyios.sinaapp.com/getAllClass.php";
     3     //2.封装URL
     4     NSURL *url=[NSURL URLWithString:path];
     5     //3.创建请求命令
     6     NSURLRequest *request=[NSURLRequest requestWithURL:url];
     7     //4.创建会话对象,通过单例方法实现
     8     NSURLSession *session=[NSURLSession sharedSession];
     9     //5.执行会话任务 通过request请求 获取data对象
    10     NSURLSessionDataTask *task=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    11         //7.json解析
    12         NSArray *arrjson=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
    13         NSLog(@"%@",arrjson);
    14         
    15     }];
    16     //6.真正的执行任务
    17     [task resume];
  • 相关阅读:
    普通锁和分布式锁
    java 正则表达式
    java 字符串转date 格式转换
    消息中间件 kafka
    数据的存储方式:对象存储、文件存储、块存储
    Exceptional Control Flow(6)
    Exceptional Control Flow(5)
    Exceptional Control Flow(4)
    Exceptional Control Flow(3)
    Exceptional Control Flow(2)
  • 原文地址:https://www.cnblogs.com/zhaochaobin/p/5324020.html
Copyright © 2020-2023  润新知