【问题标题】:How to get the values from list of objects in c#如何从c#中的对象列表中获取值
【发布时间】:2014-02-27 11:50:41
【问题描述】:

我已经调用了一个 Json Web 服务并在 c# 中得到了结果。Json Web 服务数据的格式为:

 {
  "Count": 9862,
  "Items": [
    {
      "Admin": {
        "S": "false"
      },
      "UserId": {
        "S": "e9633477-978e-4956-ab34-cc4b8bbe4adf"
      },
      "Age": {
        "N": "76.24807963806055"
      },
      "Promoted": {
        "S": "true"
      },
      "UserName": {
        "S": "e9633477"
      },
      "Registered": {
        "S": "true"
      }
    },
    {
      "Admin": {
        "S": "false"
      },
      "UserId": {
        "S": "acf3eff7-36d6-4c3f-81dd-76f3a8071bcf"
      },
      "Age": {
        "N": "64.79224276370684"
      },
      "Promoted": {
        "S": "true"
      },
      "UserName": {
        "S": "acf3eff7"
      },
      "Registered": {
        "S": "true"
      }
    },

我在 c# 中得到了这样的响应:

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:8000/userdetails");
        try
        {
            WebResponse response = request.GetResponse();
            using (Stream responseStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                return reader.ReadToEnd();
            }
        }

在最终成功获得响应后,我得到了字符串中的所有数据。然后在对象列表中解析这个字符串。现在我有对象列表,它在调试中显示计数。现在我想访问像 UserId:acf3eff7-36d6-4c3f-81dd-76f3a8071bcf 这样的值属性。我不知道如何这样做。请帮助我,我们将不胜感激。

【问题讨论】:

标签: c# json


【解决方案1】:

您可以使用以下代码从 json 中获取值:

        JObject obj = JObject.Parse(json);
        int count = (int)obj["Count"];
        var Items = obj["Items"];
        foreach (var item in Items)
              var admin = item["Admin"];

【讨论】:

    【解决方案2】:

    快速而肮脏的方式:

        //deserialize  your string json using json.net
        dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
        //get value of UserId in first Item
        var UserId = jsonObj["Items"][0]["UserId"]["S"];
    
        //OR get the value of UserId for each Item in Items
        //foreach(dynamic item in jsonObj["Items"])
          //item["UserId"]["S"];
    

    建议使用 @yousuf 提到的 c# 对象

    【讨论】:

      【解决方案3】:

      为了能够像普通 C# 对象属性一样访问 Json 属性,您需要将 json 字符串反序列化为强类型对象(例如,您可以使用 JSON.NET 进行反序列化)。

      另一个方便的工具是http://json2csharp.com/。将您的 Json 粘贴到那里,然后您可以生成适合自动映射 Json 的类定义:

      //RootObject class definition generated using json2csharp.com
      //the rest of class definition removed for brevity.
      public class RootObject
      {
          public int Count { get; set; }
          public List<Item> Items { get; set; }
      }
      ........
      ........
      //in main method
      var jsonString = .....;
      //deserialize json to strongly-typed object
      RootObject result = JsonConvert.DeserializeObject<RootObject>(jsonString);
      foreach(var item in result.Items)
      {
          //then you can access Json property like common object property
          Console.WriteLine(item.UserId.S);
      }
      

      【讨论】:

      • +1 用于 JSON.NET。出于某种原因,它是下载次数最多的 nuget 包。
      【解决方案4】:

      您正在将字符串反序列化为 c# 对象。您将需要创建代表 json 的对象。

      例如——

        public class Admin
        {
          public string S { get; set; }
        }
      
        public class UserId
        {
          public string S { get; set; }
        }
      
        public class Age
        {
          public string N { get; set; }
        }
      
        public class Promoted
        {
          public string S { get; set; }
        }
      
        public class UserName
        {
          public string S { get; set; }
        }
      
        public class Registered
        {
          public string S { get; set; }
        }
      
        public class RootObject
        {
          public Admin Admin { get; set; }
          public UserId UserId { get; set; }
          public Age Age { get; set; }
          public Promoted Promoted { get; set; }
          public UserName UserName { get; set; }
          public Registered Registered { get; set; }
        }
      

      然后使用 jsonSerializer 将 json 字符串反序列化为对象

      JavaScriptSerializer serializer = new JavaScriptSerializer();
         var result = 
                (RootObject)serializer .DeserializeObject("Json String")
      

      【讨论】:

        【解决方案5】:
            string json = @"{
            ""Name"": ""Apple"",
            ""Expiry"": new Date(1230422400000),
            ""Price"": 3.99,
            ""Sizes"": [
                ""Small"",
                ""Medium"",
                ""Large""
            ]
        }";
        
        JObject o = JObject.Parse(json);
        
        //This will be "Apple"
        string name = (string)o["Name"];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-10-31
          • 2019-05-08
          • 1970-01-01
          • 1970-01-01
          • 2014-08-07
          相关资源
          最近更新 更多