使用系统自带的NSJSONSerialization解析JSON数据
定义一下属性,我们将返回的JSOB数据一层一层转化
@property (nonatomic, copy) NSArray *results;
@property (nonatomic, copy) NSDictionary *location;
@property (nonatomic, copy) NSDictionary *now;
@property (nonatomic,copy) NSDictionary *weatherdata;
-(void)fetchFeed {
NSError *error;
//加载一个NSURL对象
//???代表key,这里使用的是心知天气的api,密钥需要自己申请.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://api.seniverse.com/v3/weather/now.json?key=???????&location=beijing&language=zh-Hans&unit=c"]];
//将请求的url数据放到NSData对象中
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//自带解析类NSJSONSerialization从response中解析出数据放到字典中
NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
//将字典转化为数组
self.results = weatherDic[@"results"];
//数组中只有一个字典元素,取出这个元素转化为字典
self.weatherdata = self.results[0];
//读取键location所对应的值,将其准换为字典
self.location = self.weatherdata[@"location"];
//读取键now所对应的值,将其准换为字典
self.now = self.weatherdata[@"now"];
}
JSON返回数据格式:
{"results":[{"location":{"id":"WX4FBXXFKE4F","name":"北京","country":"CN","path":"北京,北京,中国","timezone":"Asia/Shanghai","timezone_offset":"+08:00"},"now":{"text":"多云","code":"4","temperature":"28"},"last_update":"2017-09-04T14:55:00+08:00"}]}