在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];