JSON即JavaScript Object Natation,它是一種輕量級(jí)的數(shù)據(jù)交換格式,非常適合于服務(wù)器與客戶端的交互。
關(guān)于iOS平臺(tái)上進(jìn)行JSON解析,因?yàn)锳pple退出了自帶的SDK:NSJSONSerialization,這是一個(gè)非常好用的JSON生成和解析工具。
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ù))封包。
NSJSONSerialization Class Reference
- 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];
//IOS5自帶解析類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 );

NSJSONReadingOptions