您的位置:首页 > Web前端 > JavaScript

JSON解析--原生&AFN

2014-01-01 13:57 302 查看
#pragma mark 原生加载JSON
- (void)loadJSON
{
// 1. NSURL
NSURL *url = [NSURL URLWithString:@""];

// 2. NSURLRequest
NSURLRequest *request = [NSURLRequest requestWithURL:url];

// 3. NSURLConnection
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

if (connectionError != nil) {
NSLog(@"%@", connectionError.localizedDescription);
} else {
NSError *error = nil;

NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

if (error != nil) {
NSLog(@"%@", error.localizedDescription);
} else {
NSLog(@"%@", array);
}
}
}];
}
#pragma mark AFN加载JSON
- (void)loadJSON
{
// 1. NSURLRequest
NSURLRequest *request = [_httpClient requestWithMethod:@"GET" path:@"videos.php?format=json" parameters:nil];

// 2. 连接
AFJSONRequestOperation *op = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSArray *JSON) {

// 成功之后,直接使用反序列化出来的结果即可。
NSLog(@"%@", JSON);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
// 1> 网络访问获取数据出错
// 2> JSON的反序列化出错

NSLog(@"%@ %@", error, JSON);
}];

// 3. 将操作添加到队列或者start,操作就会启动
// 3.1 将操作添加到队列,开始多线程操作
[_httpClient.operationQueue addOperation:op];
//  [op start];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: