Question

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

So far I have:

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];

The result is:

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

}

I then :

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

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

Which produces:

{
translations =     (
            {
        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"];

without success

Was it helpful?

Solution

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

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

Now you need the translations array:

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

That is an array of dictionaries:

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top