zoukankan      html  css  js  c++  java
  • 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];
  • 相关阅读:
    MySQL数据库 : 高级查询
    ElasticSearch : High Rest Api 使用
    Java : JavaWeb和Tomcat相关
    Linux : Ubuntu 安装 RabbitMQ
    Spring : Spring Security
    Java : logback简单配置
    Spring : JPA的单独使用
    Java : Netty 入门案例
    python__PIP : 安装第三方库
    好文章收藏(持续更新)
  • 原文地址:https://www.cnblogs.com/zhaochaobin/p/5324020.html
Copyright © 2011-2022 走看看