Click here to Skip to main content
14,361,552 members

Google Translate API Usage in C#

Rate this:
4.87 (9 votes)
Please Sign up or sign in to vote.
4.87 (9 votes)
4 Oct 2019CPOL
How to add translation features to your program. This is not for bulk or commercial usage but for lite usage. For business purposes, use the paid service.

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)
    {
      // Set the language from/to in the url (or pass it into this function)
      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;

      // Get all json data
      var jsonData = new JavaScriptSerializer().Deserialize<List<dynamic>>(result);

      // Extract just the first array element (This is the only data we are interested in)
      var translationItems = jsonData[0];

      // Translation Data
      string translation = "";

      // Loop through the collection extracting the translated objects
      foreach (object item in translationItems)
      {
        // Convert the item array to IEnumerable
        IEnumerable translationLineObject = item as IEnumerable;

        // Convert the IEnumerable translationLineObject to a IEnumerator
        IEnumerator translationLineString = translationLineObject.GetEnumerator();

        // Get first object in IEnumerator
        translationLineString.MoveNext();

        // Save its value (translated text)
        translation += string.Format(" {0}", Convert.ToString(translationLineString.Current));
      }

      // Remove first blank character
      if (translation.Length > 1) { translation = translation.Substring(1); };

      // Return translation
      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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

SeaWater
Web Developer
United States United States
No Biography provided

Comments and Discussions

 
PraiseGreat Pin
Sammuel Miranda16-Oct-19 9:01
professionalSammuel Miranda16-Oct-19 9:01 
GG man! Works like a charm.
GeneralRe: Great Pin
SeaWater23-Oct-19 10:37
memberSeaWater23-Oct-19 10:37 
GeneralBad practice Pin
Eric Lapouge4-Oct-19 8:53
memberEric Lapouge4-Oct-19 8:53 
GeneralGood Practice Pin
SeaWater23-Oct-19 10:36
memberSeaWater23-Oct-19 10:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Tip/Trick
Posted 4 Oct 2019

Tagged as

Stats

4.4K views
16 bookmarked