码迷,mamicode.com
首页 > Web开发 > 详细

NSJSONSerialization的简单用法

时间:2016-06-07 23:56:17      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:

NSJSONSerialization

苹果官方给出的解析方式是性能最优越的,虽然用起来稍显复杂。

首先我们在上面已经有了我希望得到的信息的网站的API给我们的URL,在OC中,我要加载一个NSURL对象,来向网站提交一个Request。到这里需要特别注意了,iOS9的时代已经来临,我们先前在旧版本中使用的某些类或者方法都已经被苹果官方弃用了。刚刚我们向网站提交了一个Request,在以往,我们是通过NSURLConnection中的sendSynchronousRequest方法来接受网站返回的Response的,但是在iOS9中,它已经不再使用了。从官方文档中,我们追根溯源,找到了它的替代品——NSURLSession类。这个类是iOS7中新的网络接口,苹果力推之,并且现在用它完全替代了NSURLConnection。关于它的具体用法,还是蛮简单的,直接上代码(ViewController.m文件):

#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UITextView *textView;

@property (nonatomic, strong) NSMutableDictionary *dic;

@property (nonatomic, strong) NSString *text;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)didClickNSJsonButton:(id)sender {
    //GCD异步实现
    dispatch_queue_t q1 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(q1, ^{
        NSURL *url = [NSURL URLWithString:@"https://api.douban.com/v2/movie/subject/25881786"];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        //使用NSURLSession获取网络返回的Json并处理
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            self.dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSString *title = [self.dic objectForKey:@"original_title"];
            NSMutableArray *genresArray = [self.dic objectForKey:@"genres"];
            NSString *genres = [NSString stringWithFormat:@"%@/%@",[genresArray objectAtIndex:0],[genresArray objectAtIndex:1]];
            NSString *summary = [self.dic objectForKey:@"summary"];
            self.text = [NSString stringWithFormat:@"电影名称:%@\n体裁:%@\n剧情介绍:%@",title,genres,summary];
            //更新UI操作需要在主线程
            dispatch_async(dispatch_get_main_queue(), ^{
                self.textView.text = self.text;
            });
        }];
        
        [task resume];
    });
}

 

NSJSONSerialization的简单用法

标签:

原文地址:http://www.cnblogs.com/foxting/p/5568520.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!