Search code examples
c#jsongoogle-apitranslationgoogle-translation-api

How to deserialize GetStringAsync Result into translated text


I have a working method to translate text using the Google API as following;

public string TranslateText(string input, string sourceLanguage, string targetLanguage)
{
    string sourceCulture = LanguageCultureGenerator.GenerateCulture(sourceLanguage);
    string targetCulture = LanguageCultureGenerator.GenerateCulture(targetLanguage);

    string url = String.Format("https://translate.googleapis.com/translate_a/single?client=gtx&sl=
{0}&tl={1}&dt=t&q={2}",
   sourceCulture, targetCulture, Uri.EscapeUriString(input));

    HttpClient client = new HttpClient();
    string result = client.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;
}

The problem is, this class is inside of a library whose type is .Net Framework and I wanted to move it to a class library with the type of .Net Core, after I moved it I realized 'JavaScriptSerializer' can not be used in this type of library. Instead, I changed this line of code;

 //Redundant
 var jsonData = new JavaScriptSerializer().Deserialize<List<dynamic>>(result); 

with using Newtonsoft Json as following;

 var jsonData = JsonConvert.DeserializeObject(result);

Then I'm getting an error here;

var translationItems = jsonData[0];

Error is; 'Cannot apply indexing with [] to an expression of type 'object'. Any ideas how to solve this problem and make this method work with Newtonsoft Json to perform the translation operation?


Solution

  • You forgot to pass the type you want to deserialize to:

     var jsonData = JsonConvert.DeserializeObject<List<dynamic>>(result);
    

    The deserializer needs to know which .NET type it should create an instance of, or else it will create an object.