解析谷歌翻译Json C#

时间:2011-08-14 16:53:12

标签: c# json google-translate

我正在尝试使用System.Runtime.Serialization.Json库解析一些JSON。文档似乎有点稀疏,我对如何完成我需要的东西感到困惑。这是我需要解析的JSON的格式。

{
 "data": {
  "translations": [
   {
    "translatedText": "ne",
    "detectedSourceLanguage": "en"
   }
  ]
 }
}

2 个答案:

答案 0 :(得分:1)

这是一组表示您拥有的JSON数据结构的类。我选择的名称可以帮助您将类型与JSON字符串中的位置相关联。

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

[DataContract]
class DataObject
{      
  [DataMember(Name="translations")]
  public List<Translation> Translations { get; set; }
}

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

现在,以下是将JSON字符串反序列化为此结构的示例。

  string json = @"
    {
      ""data"": {
      ""translations"": [
                          {
                            ""translatedText"": ""ne"",
                            ""detectedSourceLanguage"": ""en""
                          }
                        ]
                }
    }";

  var jsonSerializer = new DataContractJsonSerializer(typeof(RootObject));
  var o = (RootObject)jsonSerializer.ReadObject(
    new MemoryStream(Encoding.Unicode.GetBytes(json)));

答案 1 :(得分:1)

    bool Clear(string str, out string res)
    {
        var ind = str.IndexOf("[[[\"");

        if (ind == -1)
        {
            res = "";
            return false;
        }

        int end = str.IndexOf("[\"\",,,", ind + 1);

        if (end == -1)
        {
            res = "";
            return false;
        }

        res = str.Substring(ind + 2, end - ind);

        var arr = res.Split(new[] {"\",\"", "\"],[\"", "[\"", "\"]"}, StringSplitOptions.RemoveEmptyEntries);

        res = "";

        for (int i = 0; i < arr.Length; i += 2)
        {
            res += arr[i];
        }

        return true;
    }
    void TranslateText(string src_lang, string dst_lang)
    {
        var input = "Some request text";

        var url = String.Format("https://translate.google.ru/translate_a/single?client=t&sl={0}&tl={1}&hl={1}&dt=bd&dt=ex&dt=ld&dt=md&dt=qc&dt=rw&dt=rm&dt=ss&dt=t&dt=at&dt=sw&ie=UTF-8&oe=UTF-8&oc=2&otf=1&trs=1&inputm=1&ssel=0&tsel=0&pc=1&q={2}", src_lang, dst_lang, input);
        var webClient = new WebClient{Encoding = Encoding.UTF8};

        webClient.DownloadStringCompleted += (sender, args) =>
        {
            string res;

            if (args.Error != null)
            {
                MessageBox.Show(args.Error.Message);

                stoped = true;

                return;
            }

            if (Clear(args.Result, out res))
            {

            }
        };

        webClient.DownloadStringAsync(new Uri(url), "your state");
    }