NSJSONSerialization使用

51 篇文章 0 订阅
- (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];
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值