2014-03-13 52 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。希望這會有所幫助.. :)

相關問題