0

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?

Max Rowe
  • 81
  • 2
  • 7
  • 1
    Possible duplicate of https://stackoverflow.com/questions/11260631/load-json-text-into-class-object-in-c-sharp/48023576#48023576 – mjwills Feb 27 '19 at 12:59

1 Answers1

1

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!)

vahdet
  • 6,357
  • 9
  • 51
  • 106