循环通过JSON数组列表

时间:2018-01-08 07:56:35

标签: c# .net json

这是我之前提出的问题的后续跟进。我试图解析一组JSON数据。我有以下数据类。我有一个列表中的数据,我可以遍历RootObject数据,但我无法循环子StoreDepartment数据。谁能告诉我如何才能做到这一点?谢谢。

string sJSON = @"[{""dateNumeric"":1216000000,""hourOfDay"":0,""customerNumber"":12,""storedepartment"":[{""department"":333,""descriptionOfDepartment"":""Department A""},{""department"":111,""descriptionOfDepartment"":""Department B""}]},{""dateNumeric"":1216000000,""hourOfDay"":3,""customerNumber"":3,""storedepartment"":[{""department"":999,""descriptionOfDepartment"":""Department X""},{""department"":888,""descriptionOfDepartment"":""Department Y""}]}]";

List<RootObject> Data = JsonConvert.DeserializeObject<List<RootObject>>(sJSON);


foreach (RootObject c in Data)
{
   debugOutput(c.dateNumeric.ToString());
   debugOutput(c.customerNumber.ToString());
}


public class RootObject
{
    public int dateNumeric { get; set; }
    public int hourOfDay { get; set; }
    public int customerNumber { get; set; }
    public List<Storedepartment> storedepartment { get; set; }
}

public class Storedepartment
{
    public int department { get; set; }
    public string descriptionOfDepartment { get; set; }
}

2 个答案:

答案 0 :(得分:1)

应该这样做吗?

foreach (RootObject c in Data)
{
   debugOutput(c.dateNumeric.ToString());
   debugOutput(c.customerNumber.ToString());
   if(c.storedepartment != null)
   {
      foreach (Storedepartment sd in c.storedepartment)
      {
      debugOutput(sd.department.ToString());
      debugOutput(sd.descriptionOfDepartment.ToString());
      }
   }
   else
   {
      debugOutput("Storedepartment was null");
   }
}

答案 1 :(得分:0)

非常简单!

foreach (var d in Data)
{
    foreach (var s in d.storedepartment)
    {               
        Console.WriteLine(s.descriptionOfDepartment);
    }
}

Working example on DotNetFiddle