简体   繁体   English

如何在 C# 中访问匿名类型 JArray 的字段?

[英]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.我想访问 json 匿名对象的值以分配给 t 对象。

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:在这种情况下,创建一个具有 json 字符串结构的类,如下所示:

   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:将 json 字符串反序列化为您的类列表,如下所示:

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.需要安装 Newtonsoft.Json 包。 You can also convert any json to class here您还可以在此处将任何 json 转换为类

By the indexer索引器

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

Object.Item Property (String) Object.Item 属性(字符串)

Gets or sets the JToken with the specified property name.获取或设置具有指定属性名称的 JToken。

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

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