Tuesday, March 19, 2013

Consuming Google Translate API v2 with C#

I spent far too much time today figuring this out (never having dealt with JSON or Google APIs before.)

It is very simple to use Google's translate services (provided you have an API key), but in the interest of sharing (and avoiding some little oopsies I hit today - such as unwrapping certain characters) here's a crude and simplified version of what I implemented.

BTW - Please note that I am using the JavaScriptSerializer below, which means that although I use a data contract (for other reasons) this particular deserializer maps by property name; ergo, the class member names MUST match the JSON property names.


[DataContract]
public class GoogleTranslation
{
    [DataMember( Name = "data" )]
    public Data Data { get; set; }
}

[DataContract]
public class Data
{
    [DataMember ( Name = "translations" )]
    public List Translations {get; set;}
}

[DataContract]
public class Translation
{
    [DataMember( Name = "translatedText" )]
    public string TranslatedText { get; set; }
}


The 3 classes above are going to be used to deserialize the returned JSON data in the method below.  BTW, you need to add three references to your project (at least, if you use the code I supply below you do - there are surely many alternatives.)

     System.Web
     System.Web.Extensions
     System.Runtime.Serialization

Sorry I didn't spend the time formatting this code (I just dumped it in) - I may do so later as it is late and I have miles to go before I do anything resembling sleep.



public string GoogleTranslate( string in_strFromLanguageCode, string in_strToLanguageCode, string in_strString )
{
    string l_strKey = "YOUR_API_KEY_GOES_HERE";
    string l_strURL = "https://www.googleapis.com/language/translate/v2?key=" + l_strKey + "&q=" + in_strString + "&source=" + in_strFromLanguageCode.ToLower() + "&target=" + in_strToLanguageCode.ToLower();
    string l_strTranslation = "";

    try
    {
        WebClient l_oWebClient = new WebClient();
        string l_strResult = "";

        //Notify the webclient we're expecting UTF-8
        l_oWebClient.Encoding = System.Text.Encoding.UTF8;
        l_strResult = l_oWebClient.DownloadString( l_strURL );

        //Unwrap special characters
        l_strResult = HttpUtility.HtmlDecode( l_strResult );

        //Deserialize JSON
        JavaScriptSerializer l_oSerializer = new JavaScriptSerializer();
        GoogleTranslation l_oTranslation = l_oSerializer.Deserialize( l_strResult );

        l_strTranslation = l_oTranslation.Data.Translations[ 0 ].TranslatedText;
    }
    catch( WebException )
    {
        //Evaluate status code
    }

    return l_strTranslation;
}


Now, there's lots of things missing you'd use in real production code (such as any basic error handling) - but that should be enough to get you rolling.

Enjoy!

No comments:

Post a Comment