AFNetworking:从Http响应中获取JSON值

时间:2014-07-09 23:02:38

标签: ios objective-c json afnetworking

我主要是一名Android开发人员,对IOS来说真的很新。我正在使用AFNetworking 1.0,因为我正在使用现有的源代码,我发送一个标准的http Post请求并返回如下数据:

   //Sending the post request and getting the result
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://testsite.org/mobile_app"]];
    [httpClient setParameterEncoding:AFFormURLParameterEncoding];
    NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST"
                                                            path:@"http://testsite.org/mobile_app/studentregister.php"
                                                      parameters:@{@"username":username, @"displayname":displayname, @"password":password, @"passwordc":passwordc, @"email":email, @"teacherCode":teacherCode}];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        // Print the response body in text
        NSLog(@"Response: %@", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    [operation start];

响应应该包含根据burp诉讼看起来像这样的JSON数据:

{"userCharLimit":"Your username must be between 5 and 25 characters in length"}

{"displaynameCharLim":"Your displayname must be between 5 and 25 characters in length"}

{"passLimit":"Your password must be between 8 and 50 characters in length"}

{"emailInvalid":"Not a valid email address"}

{"teacherCodeLength":"Your teacher code is not 5 to 12 characters"}.

如何获取这些JSON值?我已经看到了很多AFNetworking 2.0 JSON示例并发送了JSON Post请求,但我似乎找到了很多版本1.0,更不用说从标准的post请求获取值了。 任何想法或资源?

1 个答案:

答案 0 :(得分:1)

您只需要更改代码以注册AFJSONRequestOperation而不是AFHTTPRequestOperation。

[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];

然后,您可以在AFHTTPClent上使用此方法来创建实际上属于AFJSONRequestOperation类型的操作。

AFHTTPRequestOperation *operation = [httpClient HTTPRequestOperationWithRequest:request success:nil failure:nil];
[httpClient enqueueOperation:operation];