2012-06-28 61 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))。

    相关问题