简体   繁体   中英

Cant parse afnetworking json response to nsdictionary

I am attempting to call an external API with the following afnetworking request code:

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                        destination, @"destination",
                        nil];

[manager POST:baseUrl parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        completion(nil, responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    completion(error, nil);
    NSLog(@"error: %@", error);
}];

When I print out the responseObject I get the following which is the json that I expect to see:

在此处输入图片说明

However when I attempt to access the code eg responseObject[@"code"] I get some strange text:

(__NSCFNumber *) $0 = 0xb00000000000fa33 (long)4003

I then tried to parse this with NSStringwithformat %ld, but that returns:

 (__NSCFString *) $1 = 0x000060800005a850 @"-5764607523034170829"

Not sure what's going on here, whether the responseObject has even been parsed properly as an NSDictionary

any help would be appreciated

i'm not sure what is going on here, but I recommend to use Gloss framework for JSON Serializing/Deserializing to map JSON on objects directly.

http://harlankellaway.com/Gloss/

i'm not sure what is happening but it's strange

so i suggest you can Debug it step by step

What i suppose is that the number is a float, try

NSNumber *num = [responseObject objectForKey:@"code"];
int theValue = [num intValue];

This might help.

so what you have to do is, inside you success block,

NSDictionary *result = (NSDictionary *)responseObject;

for(NSDictionary *all in result){
   int code = [all objectForKey:@"code"];
}

hope this will help to your.

note : better to use model and add those objects to a mutable array .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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