UI18-使用NSJSONSerialization方法解析JSON

来源:互联网 发布:centos 搜索文件内容 编辑:程序博客网 时间:2024/05/24 00:22

使用系统自带的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 = [NSURLRequestrequestWithURL:[NSURLURLWithString:@"https://api.seniverse.com/v3/weather/now.json?key=???????&location=beijing&language=zh-Hans&unit=c"]];

    //将请求的url数据放到NSData对象中

    NSData *response = [NSURLConnectionsendSynchronousRequest:requestreturningResponse:nilerror:nil];

    //自带解析类NSJSONSerializationresponse中解析出数据放到字典中

    NSDictionary *weatherDic = [NSJSONSerializationJSONObjectWithData:responseoptions:NSJSONReadingMutableLeaveserror:&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"}]}


阅读全文
0 0
原创粉丝点击