无法在IOS应用程序中显示中文字符

时间:2014-12-10 09:36:43

标签: php ios objective-c json

我从网络服务访问以下JSON。

{"food":[{"mid":"1","name":" 首发"},{"mid":"2","name":"汤"},{"mid":"3","name":"沙拉"},{"mid":"4","name":"比萨"},{"mid":"5","name":"甜点"}]} 

但它在app中显示的是一些数字而不是实际的汉字。

请检查我的代码;这有什么不对吗?

NSString *post =[[NSString alloc] initWithFormat:@"action=%@&appId=%@&langId=%@",@"menu",appId,langId];
NSURL *url=[NSURL URLWithString:BaseURL];

NSLog(@"getMenu post : %@",post);
// Convert NSString to NSData format

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
// Create the URL Request and set the neccesary parameters

request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
//[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUnicodeStringEncoding];

NSLog(@"getMenu responce=%@",returnString);

if ([returnString isEqualToString:@""])
{
    return nil;
}
else
{

NSError *e;

NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData: returnData options:NSJSONReadingMutableContainers error: &e];;

return dataDict;

}

1 个答案:

答案 0 :(得分:1)

在最后为NSMutableURLRequest对象设置一个属性

[request setResponseEncoding:NSUTF8StringEncoding];

更新您的代码:

NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUnicodeStringEncoding];

NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

希望这有帮助。