I am trying to send a string to server by using Json Parsing. My string contains a lots of special characters like ó,æ, ø, å and many more. When i am sending the data to server without any special Character then it works just fine and response is as expected. But if there is even a single special Character then it shows error while parsing the data. I am using the following code to parse the Json String:-
NSURL *theURL = [NSURL URLWithString:urlToSendRequest];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0f];
NSData *requestData = [NSData dataWithBytes:[jsonContentToSend UTF8String] length:[jsonContentToSend length]];
[theRequest setHTTPMethod:@"POST"];
[theRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[theRequest setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
[theRequest setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[theRequest setHTTPBody: requestData];
NSURLResponse *theResponse = NULL;
NSError *theError = NULL;
NSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
NSString *data=[[NSString alloc]initWithData:theResponseData encoding:NSUTF8StringEncoding];
NSLog(@"url to send request= %@",urlToSendRequest);
NSLog(@"jsoncontenttosend= %@",requestData);
NSLog(@"response1111:-%@",data);
return data;
Here urlToSendRequest is the url and jsonContentToSend is the String i am sending to the server with Special characters.
a good way to handle this case is to send the value as base64 encoded value and after parsing it from JSON to data structure like String, one can decode the Base64 string and can get back your special characters without invalidating with actual JSON
good luck
There is an error when you create the POST data in
[jsonContentToSend length]
is the number of Unicode characters, not the number of bytes in the UTF-8 string. IfjsonContentToSend
contains non-ASCII characters, yourrequestData
will be too short, containing only a truncated part of the JSON request.You should replace this line with