新建一个SingleViewApplication应用,命名为04-JSON解析,在ViewController. m文件中,定义一个加载数据的方法,用于解析天气预报的数据,代码如下:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self loadData];
}
//加载网络数据
-(void)loadData
{
//根据请求,加载网络数据
NSURL *url=[NSURL URLWithString:@"http://www.weather.com.cn/adat/sk/101010100.html"];
NSURLRequest *request=[NSURLRequest requestWithURL:url
cachePolicy:0 timeoutInterval:10.0];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:url
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
//将二进制数据转换为字典
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
NSLog(@"%@ 市温度 %@ 风向 %@ 风力 %@",
result[@"weatherinfo"][@"city"],
result[@"weatherinfo"][@"temp"],
result[@"weatherinfo"][@"WD"],
result[@"weatherinfo"][@"WS"]);
}] resume];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
运行程序,结果如下:
如出现错误,可能是向服务器发送请求时,无法连接服务器,错误信息如下:
错误原因:从iOS9起,如果需要app发起访问网络需求,要采用https协议,如果使用http协议,则报错。
解决办法:修改Info.plist中的相关内容。
(1)在Info.plist中添加App TransportSecurity Setting,Type为Dictionary。
(2)在App TransportSecurity Setting下添加Allows Arbitrary Loads,Type为Boolean,值设置为YES。
添加完成后如下图所示:
注意:
反序列化:从服务器接收到数据之后,将二进制数据转换成NSArray或者NSDictionary类型。
序列化:在向服务器发送数据之前,将NSArray或者NSDictionary类型转换为二进制数据。