ios 使用 AFNetworking 解析 JSON 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21962230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:33:01  来源:igfitidea点击:

Parse JSON response with AFNetworking

iosobjective-cjsonxcode5afnetworking

提问by James

I've setup a JSON post with AFNetworkingin Objective-C and am sending data to a server with the following code:

我已经AFNetworking在 Objective-C 中设置了一个 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. How would I go about doing that with AFNetworking?

我正在通过相同的请求接收信息,并希望将数据发送到 NSString. 我该AFNetworking怎么做呢?

回答by Aaron Brager

responseObjectis either an NSArray or NSDictionary. You can check at runtime using isKindOfClass::

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

If you really need the string of the JSON, it's available by looking at operation.responseString.

如果您确实需要 JSON 的字符串,可以通过查看operation.responseString.

回答by RaffAl

In this case, when the web service responds with JSON, the AFNetworkingwill do the serialization for you and the responseObjectwill most likely be either a NSArrayor NSDictionaryobject.

在这种情况下,当 Web 服务以 响应时JSONAFNetworking将为您进行序列化,并且responseObject最有可能是 aNSArrayNSDictionaryobject。

Such an object should be more useful for you than string with JSONcontent.

这样的对象应该比带有JSON内容的字符串更有用。

回答by levo4ka

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/3628317answer)

检查响应对象的类型也很棒(例如https://stackoverflow.com/a/21962445/3628317答案)

回答by Chris

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.
  • Adding AFJSONRequestOperation to the http operation classes.
  • 以 AFJSONRequestOperation 合格的方式设置“接受”。
  • 将 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. Very clean.

这样做的好处是您的 responseObject 会自动为您进行 JSON 解析为字典(或数组)。很干净。

(this is for afnetworking 1.x)

(这是用于 afnetworking 1.x)