【问题标题】:ios JSON parses string values to <null>ios JSON 将字符串值解析为 <null>
【发布时间】:2013-02-13 01:54:06
【问题描述】:

我的应用程序从我的 php Web 服务接收到一个 json 响应,其中包含一组数据。 如果我在 web 服务中打印出数组,我会在我的应用程序中收到以下内容,看起来不错。

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);
}

输出:

在输出中,数组的字符串值为空,我不知道为什么。

{
            "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 返回内容类型:text/html;字符集=utf-8 知道为什么字符串解析为 null 吗?

提前致谢!

【问题讨论】:

  • 尝试在此网站jsonlint.com 上检查您的 JSON,只需粘贴您的 JSON 代码并经过验证。

标签: php ios json ios6 nsjsonserialization


【解决方案1】:

我发现了问题所在。 问题是我没有在我的 php web 服务的 mysql 查询中设置字符集。 在我的数据库中,我使用了排序规则 latin1_swedish_ci。我的 db 中的值包含一些字符,例如 'ü' 'ä' 等,这些字符无法在我的 ios 应用程序中正确解码。 在使用以下语句准备我的查询后:

$query->prepare("SET CHARACTER SET utf8");

我的服务的响应是 utf-8 编码,我可以在 json 响应中声明 NSStrings,因为 NSStrings 默认使用 utf-8 编码。

所以问题与不正确的字符串编码有关。

【讨论】:

    【解决方案2】:

    将编码设置为 NSUTF8StringEncoding。它可能会解决您的问题。

    NSLog(@"data: %@", [[NSString alloc] initWithData:downloaddata encoding:NSUTF8StringEncoding]);

    【讨论】:

      猜你喜欢
      • 2011-03-14
      • 2012-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多