在 iOS 中解析谷歌翻译 JSON [英] Parse Google Translate JSON in iOS

查看:66
本文介绍了在 iOS 中解析谷歌翻译 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 Google Translate 解析 JSON 的最佳方法是什么.

What is the best way to Parse the JSON from Google Translate.

到目前为止我有:

NSString *urlText = [NSString stringWithFormat:@"https://www.googleapis.com/language/translate/v2?key=%@&target=%@&q=%@",
                      key, target, selectedWord];

NSLog(@"%@", urlText);

NSURL *url = [NSURL URLWithString:urlText];


NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:url];
[request setHTTPMethod:@"GET"];

NSURLResponse *response;
NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

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

结果是:

{
 "data": {
  "translations": [
   {
    "translatedText": "Provincial capital",
     "detectedSourceLanguage": "de"
   }
  ]
 }

}

然后我:

if(data != nil){
NSDictionary *dic = [NSJSONSerialization
                                    JSONObjectWithData:data
                                    options:kNilOptions
                                    error:&error];
NSArray *dataObj = dic[@"data"];

NSLog(@"%@", dataObj);
}
else {
NSLog(@"ERR");
}

产生:

{
translations =     (
            {
        detectedSourceLanguage = de;
        translatedText = "Provincial capital";
    }
);
}

然后我将如何从detectedSourceLanguage 中获取de"和从translatedText 中获取Provincial capital"?我试过创建第二个数组:

How would I then go about getting the "de" from detectedSourceLanguage and "Provincial capital" from translatedText? I've tried creating a second array:

NSArray *arr2 = [dataObj valueForKey:@"detectedSourceLanguage"];

没有成功

推荐答案

调用 dic[@"data"]; 给你一个字典,而不是一个数组.所以你需要:

The call to dic[@"data"]; gives you a dictionary, not an array. So you need:

NSDictionary *data = dic[@"data"];

现在你需要翻译数组:

NSArray *translations = data[@"translations"];

这是一个字典数组:

for (NSDictionary *translation in translations) {
    NSString *detectedLanguage = translation[@"detectedSourceLanguage"];
    NSString *translatedText = translation[@"translatedText"];
}

只需将问题一步一步地分解,即可获得所需的数据.

Just break the problem down one step at a time to get to the data you need.

这篇关于在 iOS 中解析谷歌翻译 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆