public TranslationResult TranslateText(string source, string sourceLanguage, string targetLanguage) { if (!IsValidLanguageCode(targetLanguage)) { throw new Exception("Invalid Target Language Code."); } else if (!IsValidLanguageCode(sourceLanguage)) { throw new Exception("Invalid Source Language Code."); } source = Uri.EscapeDataString(source); var response = Client.GetAsync($"https://translate.yandex.net/api/v1.5/tr.json/translate?key={ApiKey}&text={source}&lang={sourceLanguage}-{targetLanguage}").Result; if (!response.IsSuccessStatusCode) { return(null); } var responseJson = response.Content.ReadAsStringAsync().Result; var token = JToken.Parse(responseJson); var result = new TranslationResult(); var text = token.Value <JArray>("text").FirstOrDefault().ToString(); result.DestinationLanguage = targetLanguage; result.SourceLanguage = sourceLanguage; result.SourceText = source; result.TranslatedText = TranslateService.FixTranslatedString(text); return(result); }
public TranslationResult TranslateText(string source, string targetLanguage) { if (!IsValidLanguageCode(targetLanguage)) { throw new Exception("Invalid Target Language Code."); } // TODO: fix source text for uri encoding. var response = Client.GetAsync($"https://translate.yandex.net/api/v1.5/tr.json/translate?key={ApiKey}&text={Uri.EscapeDataString(source)}&lang={targetLanguage}").Result; if (!response.IsSuccessStatusCode) { return(null); } var responseJson = response.Content.ReadAsStringAsync().Result; var token = JToken.Parse(responseJson); var result = new TranslationResult(); var lang = token.Value <JToken>("lang").ToString(); var splitChar = lang.IndexOf("-"); // TODO: Default if split char is not found. var sourceLang = lang.Substring(0, splitChar); var destLang = lang.Substring(splitChar + 1); var text = token.Value <JArray>("text").FirstOrDefault().ToString(); result.DestinationLanguage = destLang; result.SourceLanguage = sourceLang; result.SourceText = source; result.TranslatedText = TranslateService.FixTranslatedString(text); return(result); }