user1342592
user1342592

Reputation: 49

ios5: Sending JSON data from the iPhone to REST using POST

I am trying to send data in the JSON format to the REST api. When sending a parameter the web service does not return any data but instead gives the following error:Error parsing JSON: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.)

This is because the parameter cannot be read by the web service. But if I add this parameter directly to the URL the correct results are returned Eg:http://localhost:8080/de.vogella.jersey.final/rest/notes/63056

The following is the code for sending the parameters:

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"]];
        }

    }

Any suggestions?

Upvotes: 1

Views: 798

Answers (1)

ebandersen
ebandersen

Reputation: 2352

Your error "JSON text did not start with array or object and option to allow fragments not set" could mean two things:

  1. You're specifying that you expect the response object to be in JSON format and it is not (for example, this would happen if you're using an AFJSONRequestOperation and the server returns something other than JSON)

Fix: Get a hold of the server code and make sure it returns a valid JSON object

  1. You have not specified that you're okay with receiving something other than JSON

Fix: If you're using AFNetworking, pass in NSJSONReadingAllowFragments to [NSJSONSerialization JSONObjectWithData:options:error:] on your subclass of AFHTTPClient (Shout out to Cocoa error 3840 using JSON (iOS) for this answer).

Upvotes: 1

Related Questions