Special characters while parsing Json in iOS.

2019-08-28 13:24发布

问题:

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.

回答1:

There is an error when you create the POST data in

NSData *requestData = [NSData dataWithBytes:[jsonContentToSend UTF8String] length:[jsonContentToSend length]];

[jsonContentToSend length] is the number of Unicode characters, not the number of bytes in the UTF-8 string. If jsonContentToSend contains non-ASCII characters, your requestData will be too short, containing only a truncated part of the JSON request.

You should replace this line with

NSData *requestData = [jsonContentToSend dataUsingEncoding:NSUTF8StringEncoding];


回答2:

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