【问题标题】:JSON Response Parsing in WP7WP7 中的 JSON 响应解析
【发布时间】:2013-08-07 06:48:17
【问题描述】:

我有一个来自 web api 的 JSON 响应

{"payload":{"items":{"11204":{"title":"The Ugliest Girl?","item_id":"11204","thumb_url":"http:google.11204.jpg","teaser":"We live in the internet generationher purpose in life to her through this adversity.","language_id":"en","media_id":1,"views":"5","shares":"0"},"11228":{"title":"Depressed","item_id":"11228","thumb_url":"http:google.11228.jpg","teaser":"We all get discouraged at times, especially when things go wrong or other people hurt us. Sometimes we can seem to go through a string of disappointments that compound our sadness till we wonder.","language_id":"en","media_id":5,"views":"35","shares":"2"}} 

还有更多类似的对象

如何将其解析为 Dictionary 或以任何其他方式?响应因请求而异。

【问题讨论】:

    标签: c# json windows-phone-7


    【解决方案1】:

    你可以将你的 json 解析成一个像这样的对象:

    var parsed = JObject.Parse(Json);
    

    并得到一个特定的值:

    var value = parsed[key];
    

    【讨论】:

      【解决方案2】:

      使用json2csharp.com 之类的服务,您可以将 json 转换为 C#。鉴于您拥有的 json,您将需要稍微修改类。这里是消耗品类

      public class Item
      {
          public string title { get; set; }
          public string item_id { get; set; }
          public string thumb_url { get; set; }
          public string teaser { get; set; }
          public string language_id { get; set; }
          public int media_id { get; set; }
          public string views { get; set; }
          public string shares { get; set; }
      }
      
      public class Payload
      {
          public ICollection<Item> Items { get; set; }
      }
      

      从那里您可以使用 Json.Net 之类的库将 json 转换为这些对象。通常您可以直接转换为您的类,但由于名称中的索引,这是不可能的。所以你必须自己做一些转换。

      public Payload ConvertJson(string json)
      {
          var payload = new Payload();
      
          var container = JToken.Parse(json) as JContainer;
          if(container == null) return payload;
      
          payload.Items = new List<Item>(container.Count);
      
          foreach (var child in container)
          {
              var childJson = child.FirstOrDefault();
              if (childJson == null) continue;
      
              var item = childJson.ToObject<Item>();
              if (item.item_id == 0)
              {
                  item.item_id = Convert.ToInt32(((JProperty)child).Name);
              }
              payload.Items.Add(item);
          }
          return payload;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-27
        • 1970-01-01
        • 1970-01-01
        • 2020-03-04
        • 1970-01-01
        相关资源
        最近更新 更多