Max Rowe
Max Rowe

Reputation: 91

How do i only get the result of MS Translate Text API?

Im trying to tanslate text with the Microsoft Text Translation API. I did this with the tutorial from Microsoft link. As a result from the translator I get a jsonResponse, which looks like this:

[{"detectedLanguage":{"language":"de","score":1.0},"translations":[{"text":"Heute ist ein schöner Tag","to":"de"},{"text":"Today is a beautiful day","to":"en"}]}]

Problem: In the tutorial I serialize an Array, that holds a string (in this case only one). I know that I have to Deserialize the Object again, so i can get to each variable. I don't know how to get to the second "text"-variable(since there are 2 variables that are called "text") and it's in an Array. I only want the "Today is a beatiful day"

How can I do this?

Upvotes: 0

Views: 354

Answers (1)

vahdet
vahdet

Reputation: 6749

Using Newtonsoft, you can parse a string without creating classes for fitting the json string. As such:

// You do not have to initialize the string, you have it as the response to the api
var str = "[{\"detectedLanguage\":{\"language\":\"de\",\"score\":1.0},\"translations\":[{\"text\":\"Heute ist ein schöner Tag\",\"to\":\"de\"},{\"text\":\"Today is a beautiful day\",\"to\":\"en\"}]}]";
var result = JArray.Parse(str)
    .FirstOrDefault(x => x["detectedLanguage"]["language"].ToString() == "de")  // Find the German detection as there may be other
    ["translations"]    // get the 'translations' property
    .FirstOrDefault(x => x["to"].ToString() == "en")    // get the translation result object in for English
    ["text"];   // Get the value
Console.WriteLine(result);

Null checks are omitted to be concise and out of the scope of the original post.

EDIT: added logic for getting the proper detection as some inputs may be detected as various languages (then getting the first one recklessly would not always be nice!)

Upvotes: 1

Related Questions