AFNetworking 2.0 JSON解析

AFNetworking 2.0 JSON解析

问题描述:

这是我的代码。AFNetworking 2.0 JSON解析

(void)performHttpRequestWithURL :(NSString *)urlString :(NSMutableArray *)resultArray completion:(void (^)(NSArray *results, NSError *error))completion 
{ 
    NSURL *myUrl = [NSURL URLWithString:urlString]; 
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:myUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10]; 
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) 
    { 
     NSLog(@"请求完成"); 
     NSArray *arr; 
     arr = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingAllowFragments error:NULL]; 
     [resultArray addObjectsFromArray:arr]; 
     if (completion) { 
      completion(resultArray, nil); 
     } 
    }failure:^(AFHTTPRequestOperation *operation, NSError *error){ 
     NSLog(@"请求失败: %@", error); 
     if (completion) { 
      completion(nil, error); 
     } 
    }]; 
    [operation start]; 
} 

我只能用苹果JSON解析,我不知道如何使用AFNetworking JSON解析本身。 我没有在AFNetworking 2.0.ask找到AFJsonrequestOperaton的求助,谢谢。

+0

您是否阅读过AFNetworking文档? https://github.com/AFNetworking/AFNetworking#afhttprequestoperation – rckoenes

+1

你的问题是什么?我在这里没有看到问题。难道你找不到AFNetwork JSONRequest? –

+0

嘿,我刚刚发布和回答示例 –

无需做手工,只需设置响应序列化JSON是这样的:

.... 
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
operation.responseSerializer = [AFJSONResponseSerializer serializer]; 
您块内

现在,responseObject应该是deserialised对象(NSDictionaryNSArray取决于你的根JSON对象从所述响应)

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
    NSLog(@"Hooray, we got %@", responseObject); 
} failure:^(AFHTTPRequestOperation *operation, NSError *error){ 
    NSLog(@"Oops, something went wrong: %@", [error localizedDescription]); 
}]; 
[operation start]; 

对于以下示例代码AFNetworking 2.0工作原理:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 


NSDictionary *parameters = @{@"UserId": @"24",@"Name":@"Robin"}; 

NSLog(@"%@",parameters); 
parameters = nil; // set to nil for the example to work else you can pass data as usual 

// if you want to sent parameters you can use above code 

manager.requestSerializer = [AFJSONRequestSerializer serializer]; 

[manager POST:@"http://maps.google.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) 
{ 

    NSLog(@"JSON: %@", responseObject); 


}failure:^(AFHTTPRequestOperation *operation, NSError *error) 
{ 
     NSLog(@"Error: %@", error); 
}]; 
+4

此代码片段不清楚。你能添加更多的解释吗? – Raptor