UI18-使用NSJSONSerialization方法解析JSON

使用系统自带的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];

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

    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"}]}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值