You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JSON数组解析:如何遍历RootObject下的StoreDepartment子集合?

解决JSON子数组遍历问题

嘿,看起来你已经搞定了RootObject列表的反序列化和遍历,现在就差处理每个RootObject里的storedepartment子数组了对吧?其实方法和你遍历RootObject列表几乎一样——在现有循环里加一层嵌套的foreach循环就行,直接遍历每个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);

// 遍历每个RootObject
foreach (RootObject c in Data) {
    debugOutput(c.dateNumeric.ToString());
    debugOutput(c.customerNumber.ToString());
    
    // 遍历当前RootObject下的所有Storedepartment
    foreach (Storedepartment dept in c.storedepartment) {
        debugOutput($"部门ID: {dept.department}, 部门名称: {dept.descriptionOfDepartment}");
    }
}

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

关键说明:

  • 因为RootObject类里的storedepartment是List<Storedepartment>类型,所以它和外层的List<RootObject>一样,支持用foreach循环直接遍历。
  • 你可以根据需求在子循环里做任何操作,比如输出数据、存入数据库或者进行业务处理。

内容的提问来源于stack exchange,提问作者nemesis713

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:45:43