2013-06-26 123 views
2

我想從網頁api趕上JSON請求。當我從服務器獲得JSON格式的響應時,我會以NSData格式接收它,而不是在NSDictionnary中。我從本教程http://www.raywenderlich.com/30445/afnetworking-crash-course#(一個RESTful類的段落)中啓發了我自己,以便通過AFJSONRequestOperation更改我的客戶端的註冊操作類來實現免費的JSON解析。但是,它不起作用,我仍然以NSData格式獲得響應。JSON解析與AFNetworking

編輯:以下是完整的錯誤消息:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFData objectForKey:]: unrecognized selector sent to instance 0x753aa00' 

這裏是服務器的響應:

{"uid":"98545931","token":"98545931:176:ec0b862ba57fef88394950dd0cc41491"} 

是否有人有一個想法,爲什麼它不能被自動解析?

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseurl]; 
//Here, we tell the AFHTTPClient that the server is responding to us in JSON format. 
[client registerHTTPOperationClass:[AFJSONRequestOperation class]]; 

//Creating the dictionary containing the post parameters. 
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:username, @"username", password, @"password", nil]; 


//AUTHENTIFICATION. Retrieving token and uid by POST method. 
[client postPath:@"/auth" parameters:params 
     success:^(AFHTTPRequestOperation *operation, id responseObject) 
{ 
    NSString *text = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; 
    NSLog(@"Response: %@", text); 
    [responseField setText:text]; 
    self.jsonResponse = responseObject; 

    //The NSJSONSerialization method to transform the NSData responseObject into a dictionnary does work 
    self.jsonResponse = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil]; 

    //This NSLog makes the app crash with an unrecognized selector sent error 
    NSLog(@"User ID: %@",[jsonResponse objectForKey:@"uid"]); 
} 
     failure:^(AFHTTPRequestOperation *operation, NSError *error) 
{ 
      NSLog(@"%@", [error localizedDescription]); 
      [responseField setText:[error localizedDescription]]; 
}]; 
+0

你真的檢查過'responseObject'類嗎? – Wain

+0

完整的錯誤信息會有幫助... –

+0

對不起,添加完整的錯誤信息。至於responseObject的類,我使用isKindOfClass方法進行了檢查,它實際上是一個NSData。 –

回答

6

你缺少setDefaultHeader:value:打電話給Accept頭設置爲application/json。如果不這樣做,將不會使用JSON操作類,這意味着回退到AFHTTPRequestOperation,其使用responseData作爲其responseObject

+0

正確!標題已設置,並且所有內容都順利運行,並且來自Matt Thompson!感謝圖書館AFNetworking,並感謝正在進行的Heroku項目。 –

+2

如果這解決了您的問題,請接受答案! – fatuhoku

1

只需將默認的標頭接受設置爲application/json的值與setDefaultHeader:value:爲了告訴AFHTTPRequestOperation它實際上是我們在回調中獲得的JSON。