代码之家  ›  专栏  ›  技术社区  ›  bhavya kothari

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

  •  2
  • bhavya kothari  · 技术社区  · 12 年前

    我尝试了几种选项设置 responseSerializer JSON 但我无法将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 回复  |  直到 12 年前
        1
  •  4
  •   Yas Tabasam Denys    12 年前

    您的JSON在结尾处返回垃圾。

    enter image description here 您应该修复Web服务,使其不在JSON末尾嵌入时间戳和语言。如果您无法更改Web服务,请使用以下命令在解析json之前从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);
    

    它应该工作得很好。

        2
  •  0
  •   Rashad    12 年前

    您的数据不是有效的JSON,您可以检查 JSON Formatter 提供url或复制粘贴JSON数据并点击流程,您将看到它不是有效的JSON。

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