·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> iOS阶段学习第22天笔记(JSON数据格式介绍)

iOS阶段学习第22天笔记(JSON数据格式介绍)

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

iOS学习(OC语言)知识点整理

一、JSON数据格式  

1)概念:json是一种网络数据传输格式,有值/对象:{“A”:1,”B”:”2”…}词典;对象的序列:[,,,,,]数组两种数据类型

 

2)URLWithString 将字符串网址封装成NSURL对象 例如:  

1 NSString *urlStr=@"http://10.0.8.8/sns/my/user_list.php?number=20
2 &page=";//get  post
3 NSURL *url=[NSURL URLWithString:urlStr];

  

3)fileURLWithPath 将本地文件地址封装成NSURL的对象 例如:

1 url=[NSURL fileURLWithPath:@“Users/kingkong/JsonFile/test.json”];

 

4)initWithContentsOfURL 用于同步请求网络上的json数据  例如:  

1 NSData *json=[[NSData alloc]initWithContentsOfURL:url];

    

5)initWithData 将JSON数据解析成字符串  例如:

1 NSString *strjson=[[NSString alloc]initWithData:json encoding:NSUTF8StringEncoding];
2 NSLog(@"%@",strjson);

 

6)options:NSJSONReadingAllowFragments 可直接将json数据解析为字典对象 例如:       

1 //读取文件内容(json格式的数据)
2 NSData *jsonData=[[NSData alloc]initWithContentsOfFile:path];
3 //直接将json数据解析为字典对象
4 NSDictionary *dict1=[NSJSONSerialization JSONObjectWithData:jsonData options:
5 NSJSONReadingAllowFragments error:nil];

 

7)获取网络图片数据并保存到本地(类似下载)实例代码   

1 //获取服务器上的资源(图片数据)
2 NSData *iconData=[NSData dataWithContentsOfURL:[NSURL URLWithString:iconUrl]];
3 NSString *iconFile=[fullPath stringByAppendingPathComponent:@"icon.png"];
4  //将图片数据写入文件(保存图片到文件中)
5  [iconData writeToFile:iconFile atomically:YES];

 

8)获取JSON数据并遍历数据实例代码:  

 1 //请求的网络路径
 2 NSString *path=@"http://10.0.8.8/sns/my/user_list.php?number=20&page=";        
 3 //构造URL
 4 NSURL *url =[NSURL URLWithString:path]; 
 5 //请求获取JSON数据
 6 NSData *json=[[NSData alloc]initWithContentsOfURL:url];         
 7 //将JSON数据解析成对象
 8 id obj=[NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableContainers error:nil];
 9 //遍历JSON数据
10 if ([obj isKindOfClass:[NSDictionary class]]) {
11 NSDictionary *dict=(NSDictionary *)obj;
12 NSArray *array=[dict objectForKey:@"users"];
13 for (NSDictionary *dic in array) {
14 NSLog(@"username:%@\tuid:%@",[dic objectForKey:@"username"],[dic objectForKey:@"uid"]);
15 }
16 }

  

9)将字典集合编码成JSON数据 实例代码   

1  //构造字典数据
2 NSArray *arry=@[@"pass1234",@"123456" ];
3 NSDictionary *dic=[[NSDictionary alloc]initWithObjectsAndKeys:@"KingKong",@"username" ,@"男",@"sex",arry,@"passWord",nil];
4 //将字典集合数据转换为JSON数据类型
5 NSData *json=[NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPRettyPrinted error:nil];
6 //重新解析JSON数据
7 NSString *strjson=[[NSString alloc]initWithData:json encoding:NSUTF8StringEncoding];
8 NSLog(@"%@",strjson);

10)JSON解析工具Jason.app 【下载】 

  

11)NSDate OC中的日期函数操作【详情】