IOS 階段學習第22天筆記(JSON資料格式介紹),第22天json
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=202 &page=";//get post3 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中的日期函數操作【詳情】