coolhimanshu
coolhimanshu

Reputation: 647

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:

 {
  "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#:

    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.

Upvotes: 0

Views: 10952

Answers (5)

Faez Mehrabani
Faez Mehrabani

Reputation: 348

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

Upvotes: -2

har07
har07

Reputation: 89325

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

Another handy tool is http://json2csharp.com/. Paste your Json there then you can generate classes definitions that suitable to map the Json automatically :

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

Upvotes: 1

gitesh.tyagi
gitesh.tyagi

Reputation: 2381

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

Upvotes: 1

M.S.
M.S.

Reputation: 4433

You can use the following code to get the values from json as:

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

Upvotes: 1

Yousuf
Yousuf

Reputation: 3285

you are deserializing string to c# object. you will need to create object that reperesents the 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

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

Upvotes: 0

Related Questions