将参数传递给API时出现'/'问题

时间:2017-05-22 09:54:33

标签: objective-c nsstring nsdictionary nsdata nsjsonserialization

我有以下代码: -

a=b=0;
while(a<someValue || b<someValue){
if(condition){
   a++;
}else{
   b++;
}

}

结果是有三个'/',这使得参数以不正确的格式在API中传递。

参数: -

- (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];

1 个答案:

答案 0 :(得分:1)

这一行

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

使用一个键创建一个JSON对象,其值是序列化原始JSON对象的字符串结果。字符串中的所有"都需要使用\进行转义,这就是它的作用,即

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

由于字符串中嵌入了引号,因此不合法。所以这样做:

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

然后在打印结果字符串时会得到反斜杠的乘法,因为需要对反斜杠进行转义。

要解决此问题,请使用JSON对象,而不是其序列化。上面的一行成为:

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