2014-03-13 76 views
2

我尝试了几个选项设置responseSerializerJSON但我无法将responseObject转换为NSDictionary。问题是响应我得到是NSDataAFNetworking GET请求 - 无法将响应对象转换为NSDictionary

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.} 
+0

但是,您正在从请求中撤回的响应对象的格式是什么? – MrBr

+0

@MrBr - 它的NSData我可以将它转换为字符串 - jsonString –

+0

它可能不是一个有效的JSON然后,你可以使用'NSJSONSerialization'来分析json字符串吗? –

回答

4

你的JSON在垃圾最后回来了。

enter image description here 您应该修复您的web服务,以便不在您的JSON末尾嵌入时间戳和语言。如果您无法更改您的web服务,请使用以下命令从json中删除尾随垃圾,然后再次使用NSJSONSerialization解析垃圾。

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

然后分析该清理jsonStringNSDictionary

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

这应该只是罚款。

+0

很多很多很多感谢!!!你救了我的命! –

0

你的数据不是有效的JSON,你可以在这个JSON Formatter检查提供的网址或复制粘贴JSON数据和点击过程中,你会看到它不是一个有效的JSON。

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

相关问题