我如何只获得 MS Translate Text API 的结果?
How do i only get the result of MS Translate Text API?
我正在尝试使用 Microsoft 文本翻译 API 来翻译文本。我使用 Microsoft link 的教程完成了此操作。作为翻译器的结果,我得到了一个 jsonResponse,它看起来像这样:
[{"detectedLanguage":{"language":"de","score":1.0},"translations":[{"text":"Heute ist ein schöner Tag","to":"de"},{"text":"Today is a beautiful day","to":"en"}]}]
问题:在本教程中,我序列化了一个数组,其中包含一个字符串(在本例中只有一个)。
我知道我必须再次反序列化对象,这样我才能访问每个变量。我不知道如何获取第二个 "text"-变量(因为有 2 个变量称为 "text")并且它在一个数组中。
我只想要 "Today is a beatiful day"
我该怎么做?
使用Newtonsoft,您可以在不创建类 来匹配json 字符串的情况下解析字符串。因此:
// 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);
为简洁起见省略空检查,超出原文范围post。
编辑: 添加了用于获得正确检测的逻辑,因为某些输入可能会被检测为各种语言(然后鲁莽地获得第一个并不总是好的!)
我正在尝试使用 Microsoft 文本翻译 API 来翻译文本。我使用 Microsoft link 的教程完成了此操作。作为翻译器的结果,我得到了一个 jsonResponse,它看起来像这样:
[{"detectedLanguage":{"language":"de","score":1.0},"translations":[{"text":"Heute ist ein schöner Tag","to":"de"},{"text":"Today is a beautiful day","to":"en"}]}]
问题:在本教程中,我序列化了一个数组,其中包含一个字符串(在本例中只有一个)。 我知道我必须再次反序列化对象,这样我才能访问每个变量。我不知道如何获取第二个 "text"-变量(因为有 2 个变量称为 "text")并且它在一个数组中。 我只想要 "Today is a beatiful day"
我该怎么做?
使用Newtonsoft,您可以在不创建类 来匹配json 字符串的情况下解析字符串。因此:
// 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);
为简洁起见省略空检查,超出原文范围post。
编辑: 添加了用于获得正确检测的逻辑,因为某些输入可能会被检测为各种语言(然后鲁莽地获得第一个并不总是好的!)