iOS學習——JSON數據解析(十一)

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

 

圖片詳情可查看java

 

NSJSONSerialization提供了Json數據封包、Json數據解析,NSJSONSerialization將JSON數據轉換爲NSDictionary或NSArray解包方法,將NSDictionary、NSArray對象轉換爲JSON數據(能夠經過調用isValidJSONObject來判斷NSDictionary、NSArray對象是否能夠轉換爲JSON數 據)封包。這一篇將作簡單介紹。android


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 );


/**
* @author 張興業
*  iOS入門羣:83702688
*  android開發進階羣:241395671
*  個人新浪微博:@張興業TBOW
*/

參考:ios

http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40010946-CH1-DontLinkElementID_1web

http://www.w3school.com.cn/json/json

http://www.ibm.com/developerworks/cn/web/wa-lo-json/服務器

http://blog.sina.com.cn/s/blog_7018d3820101bdqz.htmlapp

相關文章
相關標籤/搜索