AFNetworking 2.0 JSON Parse

时间:2014-01-22 09:28:47

标签: ios json afnetworking-2

这是我的代码。

(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];
 }

我只能使用apple json解析,我不知道如何使用AFNetworking json解析自己。 我没有在AFNetworking 2.0中找到AFJsonrequestOperaton。请求帮助,谢谢。

2 个答案:

答案 0 :(得分:2)

对于下面的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);
 }];

答案 1 :(得分:0)

无需手动执行,只需将响应序列化程序设置为JSON,如下所示:

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

现在在您的块中,responseObject应该是反序列化的对象(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];