解析Google翻译Json C# [英] Parse Google Translate Json C#

查看:335
本文介绍了解析Google翻译Json C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to parse some JSON using the System.Runtime.Serialization.Json library. The documentation seems a little sparse and I'm confused as to how to accomplish what I need. Here is the format for the JSON I need to parse through.

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

推荐答案

此处是一组代表您拥有的JSON数据结构的类.我选择了可​​以帮助您将类型与JSON字符串中的位置相关联的名称.

Here is a set of classes that represent the JSON data structure you have. I have chosen names that will help you correlate the type with the location in the JSON string.

[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字符串反序列化为该结构的示例.

Now the following is an example of deserializing your JSON string into this structure.

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

这篇关于解析Google翻译Json C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆