如何将按日期分组的门店销售JSON响应重构为按部门分组?
解决方案:将销售数据从按日期分组改为按部门分组
核心思路
放弃原有的直接按日期向ResponseHandler添加数据的方式,手动构建部门为键、日期-销售额为值的数据结构,再序列化为目标JSON格式。
修改后的代码
public HttpResponseMessage GetWeeklyStoreSummary(int appid, string fromDate, string endDate, string store) { ResponseHandler response = new ResponseHandler(this.Request); WeeklyStoreSummaryHelper ws = new WeeklyStoreSummaryHelper(); try { string connectionString = GetConnectionString(appid); WeeklyStoreSummaryDBAdapter db = new WeeklyStoreSummaryDBAdapter(connectionString); // 外层字典:部门ID -> 内层字典(日期:销售额) var departmentSales = new Dictionary<string, Dictionary<string, decimal>>(); foreach (DateTime day in ws.EachDay(fromDate, endDate)) { var currentDate = day.ToShortDateString(); var result = db.GetWeeklySummary(currentDate, store); var dataTable = result.Tables[0]; // 遍历当前日期的所有部门销售数据 foreach (DataRow row in dataTable.Rows) { string deptId = row["Department"].ToString(); decimal totalSales = Convert.ToDecimal(row["Total $"]); // 若部门未在字典中,先初始化其日期销售额容器 if (!departmentSales.ContainsKey(deptId)) { departmentSales[deptId] = new Dictionary<string, decimal>(); } // 将当前日期的销售额关联到对应部门 departmentSales[deptId][currentDate] = totalSales; } } // 序列化重组后的数据为JSON(使用Newtonsoft.Json,若用.NET Core可替换为System.Text.Json) string jsonResponse = Newtonsoft.Json.JsonConvert.SerializeObject(departmentSales); return response.RequestCompleted(jsonResponse); } catch (ArgumentException a) { return response.BadRequest(a.Message); } catch (Exception e) { return response.GenericError(e.Message); } }
关键修改说明
- 数据结构重构:用
Dictionary<string, Dictionary<string, decimal>>存储最终数据,外层键是部门ID,内层键是日期,值为对应销售额,完美匹配目标JSON的层级结构。 - 遍历重组数据:不再直接调用
response.AddTable,而是遍历每个日期返回的DataTable,将部门和销售额映射到新的数据结构中。 - 自定义JSON序列化:直接序列化重组后的字典,替代原
ResponseHandler生成的按日期分组的JSON。
注意事项
- 确保项目已引用JSON序列化库:若使用.NET Framework,需添加
Newtonsoft.JsonNuGet包;若使用.NET Core/.NET 5+,可改用System.Text.Json.JsonSerializer.Serialize(departmentSales)。 - 确认
DataRow中的列名Department和Total $与数据库返回的列名完全一致,避免转换时出现键名错误。 - 若需要为无销售额的部门补全日期(设为0),可在遍历日期后,对每个部门的日期列表进行补全操作。
内容的提问来源于stack exchange,提问作者user20787927
相关产品推荐
相关产品推荐

