【问题标题】:JSON PHP and NSURLConnection with accented characters带有重音字符的 JSON PHP 和 NSURLConnection
【发布时间】:2011-07-08 15:40:01
【问题描述】:

我喜欢你的博客,通常会找到很多问题的答案,但这次我很挣扎。 我有一个 PHP Web 服务器,可以根据请求生成 JSON 输出。

另一方面,我有一个 iPhone 应用程序尝试使用请求从该服务器提取信息。

问题在于,无论何时从 PHP 服务器打印出重音字符,答案都会在 iPhone 上以字段形式出现。

这是我的 PHP 代码:

// Return a dictionary (array of element/values)
    // Partial code of the PUser class
function dictionary()
{
    $array = array();
    foreach( $this->Fields as $field )
    {
        $value = $field->GetValor(true);
        $array[$field->Nome] = utf8_encode( $value ); // I tried here several encoding methods
    }
    return $array;
}

// Header
header('Content-Type: text/html; charset=utf-8', true);

$sql    = "SELECT * FROM users";
$query  = db_query($sql);
$nbrows = db_num_rows($query);

$array  = array();

$array["Users"] = array();
$user   = new PUser;
for( $i=0; $i<$nbrows; $i++ )
{
    $user->Read($query);
    $array["Users"][] = $user->dictionary();
}

$json = json_encode( $array );
echo $json;

另一方面,我有 iPhone 代码(从网站http://stig.github.com/json-framework/ 提取):

// User action
-(IBAction)onRedo:(id)sender
{
    adapter = [[SBJsonStreamParserAdapter alloc] init];
    adapter.delegate = self;

    parser = [[SBJsonStreamParser alloc] init];
    parser.delegate = adapter;
    parser.supportMultipleDocuments = YES;

    NSString *url = @"http://wy-web-site";  // The web site I am pushing the date from

    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:url]
                                                  cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:60.0];

    connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
}

#pragma mark -
#pragma mark SBJsonStreamParserAdapterDelegate methods

- (void)parser:(SBJsonStreamParser *)parser foundArray:(NSArray *)array
{
    [NSException raise:@"unexpected" format:@"Should not get here"];
}

- (void)parser:(SBJsonStreamParser *)parser foundObject:(NSDictionary *)dict
{
    NSLog(@"parser foundObject: %@", dict );
 }

#pragma mark -
#pragma mark NSURLConnectionDelegate methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"Connection didReceiveResponse: %@ - %@, encoding: %@", response, [response MIMEType], [response textEncodingName]);
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"Connection didReceiveData of length: %u", data.length);
    NSString *str = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    NSLog(@"Data: %@", str );
    [str release];

    // Parse the new chunk of data. The parser will append it to
    // its internal buffer, then parse from where it left off in
    // the last chunk.
    SBJsonStreamParserStatus status = [parser parse:data];

    if (status == SBJsonStreamParserError)
    {
    NSLog(@"%@", [NSString stringWithFormat: @"The parser encountered an error: %@", parser.error] );
        NSLog(@"Parser error: %@", parser.error);

    } else if (status == SBJsonStreamParserWaitingForData)
    {
        NSLog(@"Parser waiting for more data");
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"Connection failed! Error - %@ %@",
      [error localizedDescription],
      [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Finish loading");
}

那么我得到的是: 从 PHP 服务器:

{"Users":[{"fs_firstname":"Jo\u00e3o","fs_midname":"da","fs_lastname":"Silva"]}

来自 iPhone (NSLog)

2011-07-08 12:00:24.620 GAPiPhone[94998:207] Connection didReceiveResponse: <NSHTTPURLResponse: 0x6f458c0> - text/html, encoding: (null)
2011-07-08 12:00:24.620 GAPiPhone[94998:207] Connection didReceiveData of length: nnn 
2011-07-08 12:00:24.620 GAPiPhone[94998:207] Data: {"Users":[{"fs_firstname":null,"fs_midname":"da","fs_lastname":"Silva","}]}
2011-07-08 12:00:24.621 GAPiPhone[94998:207] parser foundObject: {
    Users =     (
            {
        "fs_firstname" = "<null>";
        "fs_midname" = da;
        "fs_lastname" = Silva;
    }
);
}

我们可以看到我的编码在答案中为空,即使在 PHP 服务器端指定了 http 标头。

感谢您的所有意见。

【问题讨论】:

    标签: php objective-c json


    【解决方案1】:

    您的 Content-Type 标头表明数据是 UTF-8,但您似乎试图将其解析为 ASCII。如果你改变这个会发生什么:

    NSString *str = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    

    到这里:

    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    

    ?

    【讨论】:

    • 谢谢。我尝试了NSUTF8StringEncoding,结果是一样的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 2015-07-01
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    • 2018-06-22
    相关资源
    最近更新 更多