2009-08-04 79 views
1

我使用谷歌的翻译API来翻译iPhone SDK中的一些文本。我使用的网址是http://ajax.googleapis.com/ajax/services/language/translate?v=1.0从Google的翻译API获取响应时错误的编码?

一切正常,除了在某些语言中,例如波兰语,返回的字符串有时会有奇怪的东西,例如\ u0026作为字符串的一部分。它会显示为“你好吗”。为什么是这样?我得到结果的方式如下:

NSData *returnData = [NSURLConnection sendSynchronousRequest: req returningResponse: response error: error]; 
    NSString *new = [[NSString alloc] initWithData:responseData encoding: NSUTF8StringEncoding]; 

编码是否不正确?这就是为什么新字符串看起来不正确?我已经尝试了相同的文字,他谷歌翻译网页,并得到正确的翻译。


UPDATE

如果你只是去这个URL,你会看到特殊字符。我如何在应用程序中正确表示这些字符?使用上面的两行代码不能正确编码。

回答

3

的例子看起来是正确的:

\u0026quot;liberation\u0026quot; and \u0026quot;exit application\u0026quot; 

我猜是jsonEncode(htmlEncode("liberation" and "exit application"))

如果你有一个正确的JSON库,然后translatedText应该是:..."liberation" and "exit application"...,然后你只需要传递,通过一个html解码器。

\uXXXX转义符只是unicode十六进制转义符,应该由json解析器处理。

0

有趣的是,Unicode字符代码0026碰巧是和号字符,它也是URL请求中的参数分隔符。这让我想知道“req”字符串是否没有进行任何操作,而不是编码。

可能想看看对这个SO问题的回答Iphone SDk : Problem with ampersand in the URL string,看看它是否适用于您的情况。

0

响应是一个JSON字符串(阅读JSON here)。尝试在结果字符串上使用JSON解析器,然后从中检索“responseData”元素。例如,使用this framework,您的代码将如下所示:

// Your original code 
NSData *returnData = [NSURLConnection sendSynchronousRequest: req returningResponse: response error: error]; 
NSString *jsonResponse = [[NSString alloc] initWithData:responseData encoding: NSUTF8StringEncoding]; 
// JSON parsing 
SBJsonParser *parser = [SBJsonParser new]; 
id jsonObject = [parser objectWithString:jsonResponse]; 
// the result supports key-value coding 
NSString* translatedValue = [jsonObject valueForKey:@"responseData"];