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中的日期函數操作【詳情】
新聞熱點
疑難解答