简体   繁体   English

如何从C#中的对象列表中获取值

[英]How to get the values from list of objects in c#

I have Called a Json Web Service and got the result in c#.The Json Web service data is available in format: 我已经调用了Json Web服务,并在c#中得到了结果。JsonWeb服务数据的格式如下:

 {
  "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"
      }
    },

I have got the Response like this in c#: 我在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();
            }
        }

after finally successfully get the response i have got all the Data in string. 最终成功获得响应后,我将所有数据都存储在字符串中。 and then parse this string in list of objects .Now I have list of objects where it showing the count in debugging.Now I want to access the values like UserId:acf3eff7-36d6-4c3f-81dd-76f3a8071bcf like properties.I dont know how to do it.Please help me and any help will be appreciated. 然后在对象列表中解析此字符串。做到这一点。请帮助我,我们将不胜感激。

You can use the following code to get the values from json as: 您可以使用以下代码从json中获取值:

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

Quick and dirty way: 快速而肮脏的方式:

    //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"];

Advice is to use c# objects as mentioned by @yousuf 建议是使用@yousuf提到的c#对象

To be able to access Json property like common C# object property, you need to deserialize json string to strongly typed object (you can use, for example, JSON.NET to do deserialization). 为了能够像常见的C#对象属性那样访问Json属性,您需要将json字符串反序列化为强类型对象(例如,可以使用JSON.NET进行反序列化)。

Another handy tool is http://json2csharp.com/ . 另一个方便的工具是http://json2csharp.com/ Paste your Json there then you can generate classes definitions that suitable to map the Json automatically : 将您的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);
}

you are deserializing string to c# object. 您正在将字符串反序列化为c#对象。 you will need to create object that reperesents the json . 您将需要创建代表json的对象。

For example - 例如 -

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

Then deserialize json string to object using jsonSerializer 然后使用jsonSerializer将json字符串反序列化为对象

JavaScriptSerializer serializer = new JavaScriptSerializer();
   var result = 
          (RootObject)serializer .DeserializeObject("Json String")
    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"];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM