Search code examples
iosweb-servicessalesforceapex-code

ApexRest JSON Parser error when calling Salesforce webservice saying unexpected parameter using through iOS


In calling apexrest webservice for uploading attachment to specific record by calling method. So for this I hardcoded Json.

-(void)uploadToSalesforce
{   
    NSData *imagedata = UIImageJPEGRepresentation(imagePreview.image, 1.0);
    int datalength = [imagedata length];

    NSString *filename = [NSString stringWithFormat:@"Supload_iPhone_%d.jpg",datalength];

    NSString *req = [NSString stringWithFormat:@"{\n\"name\":\"%@\",\n\"Body\": \"%@\"\n,\"ParenId\":%@\"\n}",filename,imagedata,receivedrecordid];
    const char *utfString = [req UTF8String];
    NSData *postData = [NSData dataWithBytes:utfString length:strlen(utfString)];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];  
    NSMutableURLRequest *requestUrl = [[NSMutableURLRequest alloc] init ];
    [requestUrl setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/services/apexrest/Account/",receivedinstanceurl]]];
    [requestUrl setHTTPMethod:@"POST"];
    [requestUrl setValue:postLength forHTTPHeaderField:@"Content-length"];
    [requestUrl setValue:[NSString stringWithFormat:@"Bearer %@",receivedaccesstoken] forHTTPHeaderField:@"Authorization"];
    [requestUrl setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [requestUrl setHTTPBody:postData];

    NSURLResponse *response;
    NSError *err;
    NSData *reponseData = [NSURLConnection sendSynchronousRequest:requestUrl returningResponse:&response  error:&err];
    NSString *res = [[NSString alloc] initWithData:reponseData encoding:NSASCIIStringEncoding];
}

In response it says there is

[{"message":"Unexpected parameter encountered during deserialization: Name at [line:2, column:9]","errorCode":"JSON_PARSER_ERROR"}]

In console JSON seems correct but cannot parse parameter "Name".I think this is not by IOS code. Or is there some different format.


Solution

  • In the line

    NSString *req = [NSString stringWithFormat:@"{\n\"name\":\"%@\",\n\"Body\": \"%@\"\n,\"ParenId\":%@\"\n}",filename,imagedata,receivedrecordid];
    

    JSON is missing " character for ParentId key value. It should be:

    NSString *req = [NSString stringWithFormat:@"{\n\"name\":\"%@\",\n\"Body\": \"%@\"\n,\"ParenId\":\"%@\"\n}",filename,imagedata,receivedrecordid];
    

    Therefore Salesforce webservice deserialization was throwing exception.