从Google翻译中解析JSON的最佳方法是什么。
到目前为止,我有:
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";
}
);
}
那么我怎样才能从detectedText获取来自detectedSourceLanguage和“省会”的“de”? 我试过创建第二个数组:
NSArray *arr2 = [dataObj valueForKey:@"detectedSourceLanguage"];
没有成功
答案 0 :(得分:4)
对dic[@"data"];
的调用会为您提供字典,而不是数组。所以你需要:
NSDictionary *data = dic[@"data"];
现在你需要翻译数组:
NSArray *translations = data[@"translations"];
这是一系列词典:
for (NSDictionary *translation in translations) {
NSString *detectedLanguage = translation[@"detectedSourceLanguage"];
NSString *translatedText = translation[@"translatedText"];
}
只需逐步解决问题,即可获得所需的数据。