json數據解析
json的概念
JSON(JavaScript Object Notation)是一種輕量級的數據交換格式。
在實際開發中經常使用JSON來獲取服務器上的數據,并通過解析json數據獲取我們想要的數據
iOS開發使用 NSJSONSerialization(序列化)類解析json數據
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];
//iOS自帶解析類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 );
json解析過程示例
NSError *error;
//加載一個NSURL對象
NSURLRequest\*request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.weather.com.cn/data/101180601.html"]];
//將請求的url數據放到NSData對象中
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//iOS自帶解析類NSJSONSerialization從response中解析出數據放到字典中
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字典里面的內容為---%@", weatherDic );