- (IBAction)convertJSON2Foundation:(id)sender {
//需求:从网络中请求天气的JSON数据, 解析指定的值,显示到textView上
//0.天气对应url
NSURL *weatherURL = [NSURL URLWithString:@"http://www.raywenderlich.com/demos/weather_sample/weather.php?format=json"];
//1.单例session
NSURLSession *session = [NSURLSession sharedSession];
//2.数据任务
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:weatherURL completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (!error) {
//成功返回(子线程)
//4.JSON解析
NSError *jsonError = nil;
NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
//5.回到主线程显示
if (!jsonError) {
//云覆盖率
NSDictionary *dataValueDic = dataDic[@"data"];
NSDictionary *conditionDic = dataValueDic[@"current_condition"][0];
NSString *cloudCoverStr = conditionDic[@"cloudcover"];
//天气描述
NSString *weatherDesc = conditionDic[@"weatherDesc"][0][@"value"];
//请求的经纬度文本
NSString *latLonStr = dataValueDic[@"request"][0][@"query"];
//第一个天气的日期
NSString *dateStr = dataValueDic[@"weather"][0][@"date"];
dispatch_async(dispatch_get_main_queue(), ^{
//一个值占一行
self.jsonToFoundationTextView.text = [NSString stringWithFormat:@"云覆盖率:%@ \n 天气描述:%@ \n 经纬度:%@ \n 日期:%@", cloudCoverStr, weatherDesc, latLonStr, dateStr];
});
}
}
}];
//3.执行任务
[dataTask resume];
}
- (IBAction)convertFoundation2JSON:(id)sender {
//需求:把包含两个字典的数组转成NSData; 打印(转成NSString); 显示
//准备数据
NSDictionary *firstDic = @{@"username":@"gaoyuanyuan", @"age":@18, @"sex":@(NO), @"skills":@[@"Film", @"Sing"]};
NSDictionary *secondDic = @{@"username":@"wanglihong", @"age":@18, @"sex":@(YES), @"skills":@[@"Film", @"Sing"]};
NSArray *userArray = @[firstDic, secondDic];
//把数组转成JSON对象之前,判断是否可以转(验证JSON格式是否正确)
if([NSJSONSerialization isValidJSONObject:userArray]) {
//能转
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userArray options:NSJSONWritingPrettyPrinted error:&error];
if (!error) {
//显示
self.foundationToJSONTextView.text = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
}
}
NSJSONSerialization使用
最新推荐文章于 2017-09-07 10:01:36 发布