无法弄清楚这个JSON字符串

时间:2010-07-23 00:42:10

标签: iphone cocoa-touch json

我正在尝试使用谷歌翻译api来...很好地翻译一些文字,但它表现得很奇怪。当我的查询(要翻译的文本)不包含空格时,它工作正常,但是当我在查询中引入空格时,我得不到任何结果。这是我的代码:

-(void)translateText:(NSString *)originalText {

   //Construct request url
   NSString *urlString = [NSString stringWithFormat:@"http://ajax.googleapis.com/ajax/services/language/translate?q=%@&v=1.0&langpair=en%%7cde", originalText];
   NSURL *url = [NSURL URLWithString:urlString];

   // Get the contents of the URL as a string, and parse the JSON into Foundation objects
   NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];

   //Get out the translated text
   NSDictionary *results = [jsonString JSONValue];
   NSString *answer = [[results objectForKey:@"responseData"] objectForKey:@"translatedText"];

   self.translatedText = answer;
}

我无法弄清楚到底发生了什么。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您需要对originalText进行URL编码:

http://mesh.typepad.com/blog/2007/10/url-encoding-wi.html

答案 1 :(得分:1)

Ray Wenderlich最近在iPhone BTW上通过谷歌翻译和JSON进行翻译tutorial