【问题标题】:Special characters while parsing Json in iOS.在 iOS 中解析 Json 时的特殊字符。
【发布时间】:2023-04-03 03:48:01
【问题描述】:

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

 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 是我发送到服务器的带有特殊字符的字符串。

【问题讨论】:

    标签: iphone json utf-8


    【解决方案1】:

    在创建POST数据时出现错误

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

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

    您应该将这一行替换为

    NSData *requestData = [jsonContentToSend dataUsingEncoding:NSUTF8StringEncoding];
    

    【讨论】:

    • 谢谢马丁。非常感谢。这解决了我的问题。现在我得到了想要的回应。
    【解决方案2】:

    处理这种情况的一种好方法是将值作为 base64 编码值发送,并在将其从 JSON 解析为像 String 这样的数据结构后,可以解码 Base64 字符串并可以取回您的特殊字符而不会因实际 JSON 而失效

    祝你好运

    【讨论】:

    • 但我已经在使用 NSUTF8StringEncoding。 NSUTF8StringEncoding 不能处理特殊字符串吗?
    • base64和utf8编码有很大区别
    • @samfisher 是的,我同意 base64 和 utf8 编码之间存在显着差异,但是 NSUTF8StringEncoding 足够强大,可以处理所有这些。感谢您的回复。
    猜你喜欢
    • 1970-01-01
    • 2012-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 2014-11-13
    • 1970-01-01
    相关资源
    最近更新 更多