在iOS開發中與服務器進行數據交互操作,操作過程中使用最為常見的格式為JSON與XML,其中JSON較為清量,因此本篇blog就講解一下如何在iOS中進行JSON解析。
1.建立HTTP請求
(1)創建URL
NSString *URLStr = [NSString stringWithFormat:@”http://localhost:8080/MJServer/%@“, @”video”];
NSURL *URL = [NSURL URLWithString:URLStr];
(2)創建Request
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
(3)建立連接
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (connectionError || data == nil) {
[MBProgressHUD showError:@”網絡連接失敗”];
return ;
}
//NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];NSArray *videoArray = dict[@"videos"];for (NSDictionary *videoDict in videoArray) {Video *video = [Video videoWithDict:videoDict];[self.videos addObject:video];}//[self.tableView reloadData];}];
2.JSON解析使用iOS自帶的NSJSONSerialization
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];