【问题标题】:How to Send JSON String with Special Charaters in iOS?如何在 iOS 中发送带有特殊字符的 JSON 字符串?
【发布时间】:2015-06-25 18:23:31
【问题描述】:

我是 iOS 新手,我正在使用以下代码进行 API 调用。

-(NSData *)sendDataToServer:(NSString*)url :(NSString*)params
{
    NSString *postDataString = [params stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSLog(@"postDataString   :%@",postDataString);

    NSData *postData = [postDataString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    NSString *urlReq = [NSString stringWithFormat:@"%@", url];
    [request setURL:[NSURL URLWithString:urlReq]];
    [request setTimeoutInterval:180];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];

    responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];



    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

    NSLog(@"response in Server: %@",responseString);
    return responseData;

}

我将以下字符串作为参数发送到上述方法。如果我发送以下不带特殊字符的数据,我会收到成功响应。

如果我在 json 中添加任何特殊包,如 (&),我总是得到无效响应,即服务器总是返回 null。

所以任何人都可以提供任何建议,以便在使用带有特殊字符(如“&”等)的 json 字符串时获得正确的响应,

submited_data={"safty_compliance_fields":[{"safty_compliance_id":"641","fieldName":"sc1","fieldType":"editText","fieldValue":"wedgies Ig"},{"safty_compliance_id":"642","fieldName":"sc2","fieldType":"editText","fieldValue":"het &"}],"status_id":"2","product_detail":[{"dynamic_fields_id":"639","fieldName":"p1","fieldType":"editText","fieldValue":"data1"},{"dynamic_fields_id":"640","fieldName":"p2","fieldType":"editText","fieldValue":"data2"}],"inspection_id":"3","second_level":[{"questions":[{"checkListValue":"NO","checkListCommentValue":"Jgkjgjkj","sub_category_id":"452","checkListName":"sl1"},{"checkListValue":"YES","checkListCommentValue":"jk","sub_category_id":"453","checkListName":"sl2"},{"checkListValue":"YES","checkListCommentValue":"gh","sub_category_id":"455","checkListName":"sl3"},{"checkListValue":"YES","checkListCommentValue":"nm","sub_category_id":"456","checkListName":"sl4"}],"title":"sl1","entity_second_level_entry_id":"130"},{"questions":[{"checkListValue":"YES","checkListCommentValue":"Bonn","sub_category_id":"454","checkListName":"s22"}],"title":"s211","entity_second_level_entry_id":"131"}],"comment":"Jgkjgjkj","status":"Ongoing"}

【问题讨论】:

    标签: ios iphone rest ios7 nsurlconnection


    【解决方案1】:

    您发布的不是百分比编码字符串,而是原始字符串。

    【讨论】:

      猜你喜欢
      • 2015-05-28
      • 1970-01-01
      • 2020-01-08
      • 1970-01-01
      • 1970-01-01
      • 2015-09-21
      • 2018-11-08
      • 1970-01-01
      • 2020-11-14
      相关资源
      最近更新 更多