用AFNetworkingparsingJSON响应

我已经在Objective-C中用AFNetworking设置了一个JSON文章,并使用以下代码发送数据到服务器:

 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; NSDictionary *parameters = @{@"name": deviceName, @"model": modelName, @"pin": pin}; manager.requestSerializer = [AFJSONRequestSerializer serializer]; [manager.requestSerializer setValue:@"Content-Type" forHTTPHeaderField:@"application/json"]; [manager POST:@"SENSORED_OUT_URL" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"JSON: %@", responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", error); }]; 

我通过相同的请求接收信息,并希望将数据发送到NSString 。 我将如何去与AFNetworking做呢?

responseObject是一个NSArray或NSDictionary。 您可以使用isKindOfClass:在运行时检查:

 if ([responseObject isKindOfClass:[NSArray class]]) { NSArray *responseArray = responseObject; /* do something with responseArray */ } else if ([responseObject isKindOfClass:[NSDictionary class]]) { NSDictionary *responseDict = responseObject; /* do something with responseDict */ } 

如果你真的需要JSON的string,可以通过查看operation.responseString

在这种情况下,当Web服务以JSON响应时, AFNetworking将为您执行序列化,并且responseObject将很可能是NSArrayNSDictionary对象。

这样的对象应该比使用JSON内容的string更有用。

就我而言,它看起来像(也许它可以帮助)

 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; manager.requestSerializer = [AFJSONRequestSerializer serializer]; [manager POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { NSDictionary *jsonDict = (NSDictionary *) responseObject; //!!! here is answer (parsed from mapped JSON: {"result":"STRING"}) -> NSString *res = [NSString stringWithFormat:@"%@", [jsonDict objectForKey:@"result"]]; } failure:^(AFHTTPRequestOperation *operation, NSError *error) { //.... } ]; 

也将是伟大的检查types的响应对象(如https://stackoverflow.com/a/21962445/3628317答案)

我发现最好的办法就是像这样inheritanceAFHTTPClient:

 // MyHTTPClient.h #import <AFNetworking/AFHTTPClient.h> @interface MyHTTPClient : AFHTTPClient + (instancetype)sharedClient; @end // MyHTTPClient.m #import "MyHTTPClient.h" #import <AFNetworking/AFJSONRequestOperation.h> static NSString *kBaseUrl = @"http://api.blah.com/yada/v1/"; @implementation MyHTTPClient + (instancetype)sharedClient { static id instance; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ instance = [[self alloc] init]; }); return instance; } - (id)init { if (self = [super initWithBaseURL:[NSURL URLWithString:kBaseUrl]]) { self.parameterEncoding = AFJSONParameterEncoding; [self setDefaultHeader:@"Accept" value:@"application/json"]; // So AFJSONRequestOperation becomes eligible for requests. [self registerHTTPOperationClass:[AFJSONRequestOperation class]]; // So that it gets used for postPath etc. } return self; } @end 

重要的是:

  • 以AFJSONRequestOperation合格的方式设置“接受”。
  • 将AFJSONRequestOperation添加到http操作类。

那么你可以这样使用它:

 #import "MyHTTPClient.h" @implementation UserService + (void)createUserWithEmail:(NSString *)email completion:(CreateUserCompletion)completion { NSDictionary *params = @{@"email": email}; [[MyHTTPClient sharedClient] postPath:@"user" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) { completion([responseObject[@"userId"] intValue], YES); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { completion(0, NO); }]; } @end 

这样做的好处是你的responseObject自动被JSONparsing成一个字典(或数组)。 很干净。

(这是用于afnetworking 1.x)