json數(shù)據(jù)解析
json的概念
JSON(JavaScript Object Notation)是一種輕量級(jí)的數(shù)據(jù)交換格式。
在實(shí)際開(kāi)發(fā)中經(jīng)常使用JSON來(lái)獲取服務(wù)器上的數(shù)據(jù),并通過(guò)解析json數(shù)據(jù)獲取我們想要的數(shù)據(jù)
iOS開(kāi)發(fā)使用 NSJSONSerialization(序列化)類(lèi)解析json數(shù)據(jù)
NSJSONSerialization提供了Json數(shù)據(jù)封包、Json數(shù)據(jù)解析
NSJSONSerialization將JSON數(shù)據(jù)轉(zhuǎn)換為NSDictionary或NSArray
解包方法,將NSDictionary、NSArray對(duì)象轉(zhuǎn)換為JSON數(shù)據(jù)(可以通過(guò)調(diào)用isValidJSONObject來(lái)判斷NSDictionary、NSArray對(duì)象是否可以轉(zhuǎn)換為JSON數(shù) 據(jù))封包
json數(shù)據(jù)封包
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"key1",@"value2",@"key2",@"value3",@"key3", nil];
// isValidJSONObject判斷對(duì)象是否可以構(gòu)建成json對(duì)象
if ([NSJSONSerialization isValidJSONObject:dic]){
NSError *error;
// 創(chuàng)造一個(gè)json從Data, NSJSONWritingPrettyPrinted指定的JSON數(shù)據(jù)產(chǎn)的空白,使輸出更具可讀性。
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"json data:%@",json);
}
json數(shù)據(jù)解析
NSError *error;
//加載一個(gè)NSURL對(duì)象
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.weather.com.cn/data/101120101.html"]];
//將請(qǐng)求的url數(shù)據(jù)放到NSData對(duì)象中
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//iOS自帶解析類(lèi)NSJSONSerialization從response中解析出數(shù)據(jù)放到字典中
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 );
json解析過(guò)程示例
NSError *error;
//加載一個(gè)NSURL對(duì)象
NSURLRequest\*request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.weather.com.cn/data/101180601.html"]];
//將請(qǐng)求的url數(shù)據(jù)放到NSData對(duì)象中
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//iOS自帶解析類(lèi)NSJSONSerialization從response中解析出數(shù)據(jù)放到字典中
NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
NSDictionary *weatherInfo = [weatherDic objectForKey:@"weatherinfo"];
txtView.text = [NSString stringWithFormat:@"今天是 %@ %@ %@ 的天氣狀況是:%@ %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]];
NSLog(@"weatherInfo字典里面的內(nèi)容為---%@", weatherDic );