在iOS中解析Json时的特殊字符. [英] Special characters while parsing Json in iOS.

查看:337
本文介绍了在iOS中解析Json时的特殊字符.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Json解析将字符串发送到服务器.我的字符串包含许多特殊字符,例如ó,æ,ø,å等.当我将数据发送到服务器时没有任何特殊字符时,它就可以正常工作并且响应是预期的.但是,即使只有一个特殊字符,在解析数据时也会显示错误. 我正在使用以下代码来解析Json字符串:-

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;

此处 urlToSendRequest 是URL,而 jsonContentToSend 是我要发送到服务器的带有特殊字符的字符串.

Here urlToSendRequest is the url and jsonContentToSend is the String i am sending to the server with Special characters.

推荐答案

在其中创建POST数据时出现错误

There is an error when you create the POST data in

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

[jsonContentToSend length]是Unicode字符数,而不是其中的字节数 UTF-8字符串.如果jsonContentToSend包含非ASCII字符,则您的requestData将太短,仅包含JSON请求的截断部分.

[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.

您应该将这一行替换为

NSData *requestData = [jsonContentToSend dataUsingEncoding:NSUTF8StringEncoding];

这篇关于在iOS中解析Json时的特殊字符.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆