简体   繁体   中英

How can i access fields of anonymous typed JArray in C#?

string sampleString = "[{\"id\":\"1\",\"status\":302},{\"id\":\"2\",\"status\":302},{\"id\":\"3\",\"status\":302},{\"id\":\"4\",\"status\":302}]";     
JArray json = JArray.Parse(sampleString );
TempValue t;
foreach(JObject obj in json)
{
t = new TempValue {
id =//id of json,
status=//state of json
};
}

i want to access value of json anonymous objec to assign to t object.

It is always good to work with a typed object to avoid typing mistakes. In this case create a class with the structure of the json string like so:

   public class StatusObj
   {
     public string id { get; set; }
     public int status { get; set; }
   }

The deserialize the json string to list of your class like so:

List<StatusObj> obj = JsonConvert.DeserializeObject<List<StatusObj>>(sampleString);

And then you can loop through the list like so:

foreach (var item in obj)
 {
   var id = item.id;
   var status = item.status;
 }

The whole code look like this:

  class Program
{
    static void Main(string[] args)
    {
        string sampleString = "[{\"id\":\"1\",\"status\":302},{\"id\":\"2\",\"status\":302},{\"id\":\"3\",\"status\":302},{\"id\":\"4\",\"status\":302}]";

        List<StatusObj> obj = JsonConvert.DeserializeObject<List<StatusObj>>(sampleString);

        foreach (var item in obj)
        {
            var id = item.id;
            var status = item.status;
        }

    }
}

public class StatusObj
{
    public string id { get; set; }
    public int status { get; set; }
}

NB. Newtonsoft.Json package needed to be installed. You can also convert any json to class here

By the indexer

foreach(JObject obj in json)
{
    t = new TempValue {
    id = obj["id"].ToString() ,
      ...   
};

Object.Item Property (String)

Gets or sets the JToken with the specified property name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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