在之前的[《](http://blog.csdn.net/xyz_lmn/article/details/9164019)[iOS學習——xml數據解析(九)》](http://blog.csdn.net/xyz_lmn/article/details/9164019)介紹了xml數據解析,這一篇簡單介紹一下Json數據解析。JSON 即 JavaScript Object Natation,它是一種輕量級的數據交換格式,非常適合于服務器與客戶端的交互,[Json語法參考](http://blog.csdn.net/xyz_lmn/article/details/JSON)。關于在iOS平臺上進行JSON解析,已經有很多第三方的開源項目,比如TouchJson,JSONKit,SBJon等,自從iOS5.0以后,蘋果SDK推出了自帶的JSON解決方案NSJSONSerialization,這是一個非常好用的JSON生成和解析工具,效率也是比其他第三方開源項目的高很多,詳情可看下圖。

[圖片詳情可查看](http://arthurchen.blog.51cto.com/2483760/723910)
NSJSONSerialization提供了Json數據封包、Json數據解析,NSJSONSerialization將JSON數據轉換為NSDictionary或NSArray解包方法,將NSDictionary、NSArray對象轉換為JSON數據(可以通過調用isValidJSONObject來判斷NSDictionary、NSArray對象是否可以轉換為JSON數 據)封包。這一篇將做簡單介紹。

**Json數據封包**
~~~
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"key1",@"value2",@"key2",@"value3",@"key3", nil];
// isValidJSONObject判斷對象是否可以構建成json對象
if ([NSJSONSerialization isValidJSONObject:dic]){
NSError *error;
// 創造一個json從Data, NSJSONWritingPrettyPrinted指定的JSON數據產的空白,使輸出更具可讀性。
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"json data:%@",json);
}
~~~
**Json數據解析**
~~~
NSError *error;
//加載一個NSURL對象
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.weather.com.cn/data/101120101.html"]];
//將請求的url數據放到NSData對象中
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//IOS5自帶解析類NSJSONSerialization從response中解析出數據放到字典中
NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
NSDictionary *weatherInfo = [weatherDic objectForKey:@"weatherinfo"];
NSString *text = [NSString stringWithFormat:@"今天是 %@ %@ %@ 的天氣狀況是:%@ %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]];
NSLog(@"weatherInfo:%@", text );
~~~
- 前言
- (一)——ios搭建開發環境
- (二)——Hello iOS
- (三)——iOS系統架構
- (四)——iOS應用程序生命周期
- (五)——UI基礎UIWindow、UIView
- (六)——ViewController
- (七)——UI基礎UIButton
- (八)——iOS網絡通信http之NSURLConnection
- (九)—— xml數據解析
- (十)——iOS真機調試
- (十一)——JSON數據解析
- (十二)——iOS國際化
- (十三)——獲取手機信息(UIDevice、NSBundle、NSLocale)
- (十四)——打電話、發短信
- (十五)——數據庫操作(SQLite)
- (十六)——數據庫操作(使用FMDB)
- (十七)——文件操作(NSFileManager)
- Swift初學習