V-Xtreme
V-Xtreme

Reputation: 7333

Converting in to JSON in objective c

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}': '' }

Upvotes: 0

Views: 213

Answers (1)

Chris Heyes
Chris Heyes

Reputation: 366

  1. Don't use NSJSONWritingPrettyPrinted, you don't want or need any whitespace in there.

  2. Use...

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

Assuming your dictionary is correct and your Server-side parsing is correct this should work for you.

Also, please post the results or your debug logs in future... i.e. the actual request your sending and the actual response you get from the server.

Upvotes: 1

Related Questions