【问题标题】:Good but easy method of deserializing JSON data in c#在 c# 中反序列化 JSON 数据的好方法
【发布时间】:2015-12-22 01:19:47
【问题描述】:

我已经苦苦挣扎了很长一段时间,但现在我成功地从 Web API 中提取 JSON 数据。

到目前为止我的代码(目前只有一个测试 sn-p):

var url = "http://www.trola.si/bavarski";
string text;

HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = WebRequestMethods.Http.Get;
request.Accept = "application/json";

var json = (HttpWebResponse)request.GetResponse();


using (var sr = new StreamReader(json.GetResponseStream()))
{
    text = sr.ReadToEnd();
}

就拉取数据而言,这没问题,对吧?

好吧,这里有点令人困惑。网上资源很多,而且各有千秋。我是否需要创建一个类来保存数据和{ get; set; }

RESTsharp 或 Json.NET 会让我的工作更轻松吗?任何建议表示赞赏。

【问题讨论】:

标签: c# json visual-studio rest uwp


【解决方案1】:

您不需要任何第三方 JSON 库。

  1. 获取数据到一个字符串。你已经这样做了。

  2. 创建您的数据类。我喜欢 igrali 使用 Visual Studio 来做这件事的想法。但是,如果数据很简单,只需自己编写类:

        [DataContract]
        public class PersonInfo
        {
            [DataMember]
            public string FirstName { get; set; }
    
            [DataMember]
            public string LastName { get; set; }
        }
    
  3. 从字符串反序列化到类:

我喜欢使用这个通用助手:

    public static T Deserialize<T>(string json)
    {
        using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            T obj = (T)serializer.ReadObject(stream);
            return obj;
        }
     }

然后这样称呼它:

            PersonInfo info = (PersonInfo)JsonHelper.Deserialize<PersonInfo>(s);

【讨论】:

    【解决方案2】:

    首先,您需要创建代表您收到的 JSON 模型的类。这样做的方法不止一种 - 您可以使用 json2csharp 甚至更好的 Visual Studio 功能,称为 Paste JSON As Classes(在以下位置找到它:编辑 -> 选择性粘贴 -> 将 JSON 粘贴为类)。

    一旦你有了这些类,你就可以使用 Json.NET 来帮助你处理 JSON 响应。您可能希望将收到的字符串 (JSON) 反序列化为 C# 对象。为此,您只需调用JsonConvert.DeserializeObject 方法即可。

    var myObject = JsonConvert.DeserializeObject<MyClass>(json);
    

    其中MyClass 是您要反序列化的任何类型。

    【讨论】:

      【解决方案3】:

      有一个 WebApi 客户端会为您处理所有的序列化。

      http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

      这是一个示例:

      using (var client = new HttpClient())
      {
          client.BaseAddress = new Uri("http://localhost:9000/");
          client.DefaultRequestHeaders.Accept.Clear();
          client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
      
          // New code:
          HttpResponseMessage response = await client.GetAsync("api/products/1");
          if (response.IsSuccessStatusCode)
          {
              Product product = await response.Content.ReadAsAsync<Product>();
              Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
          }
      }
      

      【讨论】:

        【解决方案4】:

        Json.net 在这方面有很大帮助。您可以反序列化为匿名类型或 POCO 对象。我希望以下解决方案可以帮助您入门。

        async Task Main()
        {
            using (var client = new HttpClient())
            {
                using (var request = new HttpRequestMessage())
                {
                    request.RequestUri = new Uri("http://www.trola.si/bavarski");
                    request.Headers.Accept.Add(new  MediaTypeWithQualityHeaderValue("application/json"));
                    request.Method = HttpMethod.Get;
                    var result = await client.SendAsync(request);
                    string jsonStr = await result.Content.ReadAsStringAsync();
                    Result obj = JsonConvert.DeserializeObject<Result>(jsonStr);
                    obj.Dump();
                }
            }
        }
        
        // Define other methods and classes here
        public class Result
        {
            [JsonProperty(PropertyName = "stations")]
            public Station[] Stations { get; set;}
        }
        
        public class Station
        {
            [JsonProperty(PropertyName = "number")]
            public string Number { get; set; }
            [JsonProperty(PropertyName = "name")]
            public string Name { get; set; }
            [JsonProperty(PropertyName = "buses")]
            public Bus[] Buses { get; set; }
        }
        
        
        public class Bus
        {
            [JsonProperty(PropertyName = "direction")]
            public string Direction { get; set; }
            [JsonProperty(PropertyName = "number")]
            public string Number { get; set; }
            [JsonProperty(PropertyName = "arrivals")]
            public int[] Arrivals { get; set; }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多