0

I have following code to convert my employee object in to JSON file :

  NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys:emp.empName,@"name",emp.empId,@"empid",emp.empAddress,@"address",emp.mobile,@"mobile",nil];

    NSData *jsonData=[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *str=[[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"data =%@",str);

by using this code i am getting the JSON file. But I want to send this json as a httprequest body i have following code for this:

      NSData *requestBody=[[NSString stringWithFormat:@"%@",str] dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:requestBody];
NSURLConnection *conn=[[NSURLConnection alloc]initWithRequest:request delegate:self];

But i am getting wrong json at the server side which cannot be parsed. Please suggest some solution on this problem. If i send JSON Data directly i got following json at server side which is wrong:

{ '{\n  "name" : "vx",\n  "mobile" : "8888888",\n  "empid" : "96",\n  "address" : "addre"\n}': '' }
4

1 回答 1

1
  1. 不要使用 NSJSONWritingPrettyPrinted,你不需要或不需要任何空格。

  2. 利用...

NSString *str=[[[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

假设您的字典是正确的并且您的服务器端解析是正确的,这应该适合您。

另外,请在以后发布结果或调试日志......即您发送的实际请求和您从服务器获得的实际响应。

于 2012-05-31T10:18:39.417 回答