2012-06-28 67 views
1

我正嘗試將JSON格式的數據發送到REST API。發送參數時,Web服務不會返回任何數據,而是會給出以下錯誤:解析JSON時出錯:錯誤域= NSCocoaErrorDomain代碼= 3840「操作無法完成(可可錯誤3840.)」(JSON文本沒有不以數組或對象和選項開始,以允許片段未設置。)ios5:使用POST將JSON數據從iPhone發送到REST

這是因爲Web服務無法讀取參數。 但是,如果我直接將此參數添加到URL,則返回正確的結果例如:http:// localhost:8080/de.vogella.jersey.final/rest/notes/63056

以下是發送參數:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://localhost:8080/de.vogella.jersey.final/rest/notes/"]]; 
    [request setHTTPMethod:@"POST"]; 
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 

    NSString *postString = @"{\"notes\":\"63056\"}"; 
    NSLog(@"Request: %@", postString); 
    // NSString *postString = @""; 


    [request setValue:[NSString stringWithFormat:@"%d",[postString length]] forHTTPHeaderField:@"Content-length"]; 
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]]; 




    NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ]; 
    NSLog(@"Return Data%@",returnData); 


    //Getting the task types from the JSON array received 
    NSMutableArray *jsonArray =[NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&error]; 
    NSLog(@"jsonArray is %@",jsonArray); 
    taskTypes =[[NSMutableArray alloc]init ]; 
    if (!jsonArray) { 
     NSLog(@"Error parsing JSON: %@",error); 
    } else { 
     for(NSDictionary *taskType in jsonArray) { 


      [taskTypes addObject:[taskType objectForKey:@"TaskName"]]; 
     } 

    } 

有什麼建議嗎?

回答

0

你的錯誤「JSON文本沒有用數組或對象,並選擇開始允許片段未設置」可能意味着兩兩件事:

  1. 你指定您所期望的響應對象是JSON格式它不是

修復(例如這個,如果你正在使用AFJSONRequestOperation服務器返回JSON比其他的東西會發生):獲取服務器代碼的保持,並確保它返回一個有效的JSON對象

  • 您還沒有指定您能夠接受接受其他的東西比JSON
  • 修復:如果您使用AFNetworking,傳遞NSJSONReadingAllowFragments爲[NSJSONSerialization JSONObjectWithData:options:error:]在您的AFHTTPClient的子類上(對此答案大聲輸入Cocoa error 3840 using JSON (iOS))。

    相關問題