Search code examples
objective-cnsstringnsdictionarynsdatansjsonserialization

issue with '/' while passing parameter to API


I have the following code:-

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    NSData *data = [surveyAnswerForCurrentSurvey dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *answerJson = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSMutableDictionary *answer = [answerJson mutableCopy];

    if([answer valueForKey:question.name] != nil){
        [answer setObject:textField.text forKey:question.name];
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:[answer copy] options:0 error:nil];
    NSLog(@"ns data is %@",jsonData);
    NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"json string:%@", json);
    NSDictionary *answersDict = @{@"answers_json":json};

    NSData *answersAsData = [NSJSONSerialization dataWithJSONObject: answersDict options:0 error:nil];
    NSString *answersJSONStringify = [[NSString alloc] initWithData: answersAsData encoding:NSUTF8StringEncoding];
    parameters = @{@"survey_answer":answersJSONStringify};

    [self submitSurveyAnswer];

the result is having three '/' which is making the parameter to be passed in API in improper format.

parameter:-

{ "survey_answer" = "{\"answers_json\":\"{\\\"7d2c591c-9056-405c-9509-03266842b7‌​e5\\\":[\\\"1\\\"],\‌​\\"4090442c-90ce-42c‌​2-aae8-7c812b7c0f04\‌​\\":\\\"test from postman\\\",\\\"54bdcf13-e500-418a-8bab-d0639e7e1e28\\\":\\\‌​"2\\\",\\\"63bb0722-‌​7099-4820-a400-36b89‌​38c6ae8\\\":\\\"hell‌​o\\\",\\\"f884a7d1-f‌​9d9-4563-bb6e-945386‌​64f3bd\\\":\\\"test from cms and iphone\\\",\\\"ed3acc20-4ae4-493e-ac55-4d2d0f282886\\\":\\\"‌​1\\\"}\"}"; }

Solution

  • This line

    NSDictionary *answersDict = @{@"answers_json":json};
    

    Creates a JSON object with one key whose value is the string result of serialising your original JSON object. All of the " in the string need to be escaped with \ so this is what it does, i.e.

    { "answer" : "{ "foo" : "bar" }" }
    

    Is not legal because of the embedded quotes in the string. So it does this:

    { "answer" : "{ \"foo\" : \"bar\" }" }
    

    Then you get multiplication of backslashes when you print the resulting string because the backslashes need to be escaped.

    To fix the problem, use the JSON object, not its serialisation. the line above becomes:

    NSDictionary *answersDict = @{@"answers_json": [answer copy]};