您的位置:首页 > 产品设计 > UI/UE

UI18-使用NSJSONSerialization方法解析JSON

2017-09-04 14:57 232 查看
使用系统自带的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"}]}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  json ios