Introduction
We would like to easily translate a string of text to another language. The results returned from the Google Translate API are very cryptic. They are in the form of a JSON jagged array. It is even harder when you have to translate multiple sentences. This tip describes how to properly use the free API using C#.
Requirements
You must add a reference to System.Web.Extensions
. Then add the following using
directives:
using System.Net.Http;
using System.Collections;
using System.Web.Script.Serialization;
Example Translate Function
Add the following function to your code:
public string TranslateText(string input)
{
string url = String.Format
("https://translate.googleapis.com/translate_a/single?client=gtx&sl={0}&tl={1}&dt=t&q={2}",
"en", "es", Uri.EscapeUriString(input));
HttpClient httpClient = new HttpClient();
string result = httpClient.GetStringAsync(url).Result;
var jsonData = new JavaScriptSerializer().Deserialize<List<dynamic>>(result);
var translationItems = jsonData[0];
string translation = "";
foreach (object item in translationItems)
{
IEnumerable translationLineObject = item as IEnumerable;
IEnumerator translationLineString = translationLineObject.GetEnumerator();
translationLineString.MoveNext();
translation += string.Format(" {0}", Convert.ToString(translationLineString.Current));
}
if (translation.Length > 1) { translation = translation.Substring(1); };
return translation;
}
Set the from/to language in the following line. In this case, en (from language) and es (to language):
string url = String.Format
("https://translate.googleapis.com/translate_a/single?client=gtx&sl={0}&tl={1}&dt=t&q={2}",
"en", "es", Uri.EscapeUriString(input));
Then call your code:
string translatedText = TranslateText(text);
Points of Interest
You will only be allowed to translate about 100 words per hour using the free API. If you abuse this, Google API will return a 429 (Too many requests) error.
History
- 10/4/2019: Original version