简体   繁体   English

使用AFNetworking解析JSON响应

[英]Parse JSON response with AFNetworking

I've setup a JSON post with AFNetworking in Objective-C and am sending data to a server with the following code: 我在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);
}];

I'm receiving information through the same request, and want to send the data to a NSString . 我通过相同的请求收到信息,并希望将数据发送到NSString How would I go about doing that with AFNetworking ? 我如何使用AFNetworking做到这AFNetworking

responseObject is either an NSArray or NSDictionary. responseObject是NSArray或NSDictionary。 You can check at runtime using isKindOfClass: : 您可以使用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 */
}

If you really need the string of the JSON, it's available by looking at operation.responseString . 如果你真的需要JSON的字符串,可以通过查看operation.responseString获得它。

In this case, when the web service responds with JSON , the AFNetworking will do the serialization for you and the responseObject will most likely be either a NSArray or NSDictionary object. 在这种情况下,当Web服务使用JSON响应时, AFNetworking将为您执行序列化,而responseObject很可能是NSArrayNSDictionary对象。

Such an object should be more useful for you than string with JSON content. 这样的对象应该比具有JSON内容的字符串更有用。

In my case, it's looks like (maybe it can helps) 在我的情况下,它看起来像(也许它可以帮助)

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) {
          //....
      }
 ];

Also would be great to check type of response object (like https://stackoverflow.com/a/21962445/3628317 answer) 也很好检查响应对象的类型(如https://stackoverflow.com/a/21962445/3628317答案)

I find it works best to subclass AFHTTPClient like so: 我觉得最好将AFHTTPClient子类化为:

//  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

The important bits are: 重要的是:

  • Setting the 'Accept' in such a way that AFJSONRequestOperation becomes eligible. 以AFJSONRequestOperation符合条件的方式设置“接受”。
  • Adding AFJSONRequestOperation to the http operation classes. 将AFJSONRequestOperation添加到http操作类。

Then you can use it like so: 然后你可以像这样使用它:

#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

The beauty of this is that your responseObject is automatically JSON-parsed into a dictionary (or array) for you. 这样做的好处在于,您的responseObject会自动被JSON解析为字典(或数组)。 Very clean. 很干净。

(this is for afnetworking 1.x) (这是针对afnetworking 1.x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM