我的应用程序从我的php Web服务收到一个json响应,其中包含一组数据。 如果我在webservice中打印出数组,我在我的应用程序中收到以下内容,看起来不错。
NSLog(@"data: %@", [[NSString alloc] initWithData:downloaddata encoding:NSASCIIStringEncoding]);
输出:
[0] => Array
(
[id] => 3
[title] => some title //MySQL varchar(60), utf8_unicode_ci
[description] => some description //MySQL text, utf8_unicode_ci
[type] => AUDIO //MySql enum
[created] => 2013-02-25 00:00:00
[edited] => 2013-02-25 00:00:00
[version] => 1
[courserooms_id] => 1
)
[1] => Array
(
[id] => 4
[title] => some other title
[description] => some other description
[type] => MOVIE
[created] => 2013-02-12 00:00:00
[edited] => 2013-02-14 00:00:00
[version] => 1
[courserooms_id] => 1
)
在iOS中,我使用NSJSONSerialization解析收到的数据。
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:downloaddata
options:kNilOptions
error:&error];
NSLog(@"error: %@", [error localizedDescription]);
NSLog(@"json: %@", json);
}
输出:
在输出中,数组的字符串值为null,我不知道为什么。
{
"courserooms_id" = 1;
created = "2013-02-25 00:00:00";
description = "<null>";
edited = "2013-02-25 00:00:00";
id = 3;
title = "<null>";
type = AUDIO;
version = 1;
},
{
"courserooms_id" = 1;
created = "2013-02-12 00:00:00";
description = "<null>";
edited = "2013-02-14 00:00:00";
id = 4;
title = "<null>";
type = MOVIE;
version = 1;
}
我的php webservice返回content-type:text / html;字符集= utf-8的 知道为什么字符串解析为null?
提前致谢!
答案 0 :(得分:0)
将编码设置为NSUTF8StringEncoding。它可以解决你的问题。
NSLog(@“data:%@”,[[NSString alloc] initWithData:downloaddata encoding:NSUTF8StringEncoding]);
答案 1 :(得分:0)
我弄明白了这个问题。 问题是我没有在我的php web服务上的mysql查询中设置charset。 在我的数据库中,我使用了整理latin1_swedish_ci。我的数据库中的值包含一些字符,如'ü''ä'等,无法在我的ios应用程序中解码。 用以下语句准备我的查询后:
$query->prepare("SET CHARACTER SET utf8");
我服务的响应是utf-8编码,我可以从json响应中声明NSStrings,因为NSStrings默认使用utf-8编码。
所以问题与字符串的错误编码有关。