AFNetworking GET请求 - 无法将responseObject转换为NSDictionary

时间:2014-03-13 06:09:56

标签: ios objective-c afnetworking-2

我尝试了几个选项设置responseSerializerJSON,但我无法将responseObject转换为NSDictionary。问题是我得到的答案是NSData

    NSString *baseURLString = @"Your URL?";
    NSString *str = @"adult=false&gender=male";

    NSString *url = [NSString stringWithFormat:@"%@%@",baseURLString,str];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id  responseObject) {
        // do whatever you'd like here; for example, if you want to convert
        // it to a string and log it, you might do something like:

        NSLog(@"responseObject %@",responseObject);

        NSString *jsonString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"%@", jsonString);


    NSError* error;
    NSDictionary* json = [NSJSONSerialization
                          JSONObjectWithData:responseObject
                          options:NSJSONReadingMutableContainers
                          error:&error];
    NSLog(@"json %@",json);

    if (error) {
        NSLog(@"%@",[error description]);
    }



    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
}];

NSLog(@"%@",[error description]);给出错误如下:

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. 
(Cocoa error 3840.)" (Garbage at end.) 
UserInfo=0xa7c5440 {NSDebugDescription=Garbage at end.}

2 个答案:

答案 0 :(得分:4)

你的JSON最后会带回垃圾回来。

enter image description here 您应修复您的Web服务,以便在JSON结尾处不嵌入时间戳和语言。如果您无法更改Web服务,请使用以下内容从json中删除尾随垃圾,然后再使用NSJSONSerialization进行解析。

NSRange range = [jsonString rangeOfString:@"}" options:NSBackwardsSearch];
jsonString = [jsonString substringToIndex:range.location + 1];

然后将已清理的jsonString解析为NSDictionary

NSData *newJSONData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization
                          JSONObjectWithData:newJSONData
                          options:NSJSONReadingMutableContainers
                          error:&error];
    NSLog(@"json %@",json);

它应该可以正常工作。

答案 1 :(得分:0)

您的数据不是有效的JSON,您可以在此JSON Formatter中查看提供网址或复制粘贴JSON数据并点击进程,您将看到它不是有效的JSON。

它无效的原因是它在响应结束时包含This page was created in 0.0048439502716064 seconds此消息。如果在服务器端有控制而不是尝试最后停止发送此行或尝试删除此行并将其转换为NSDictionary。希望这有助于.. :))