我有这个数据
并希望像
一样返回
我写了这段代码
[HttpGet]
public JsonResult GetTime()
{
var data = _db.CourseTimes.Select(c => new { c.Day, c.StartTime, c.EndTime })
.GroupBy(c=>c.Day).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
答案 0 :(得分:1)
您必须将数据转换为只具有Start和Stop属性的类;您可能还需要调用.ToDictionary
才能让JSON转换器知道您真正想要的内容:
// Class for Database input
public class Course {
public string Day { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
}
// Class for JSON output
public class StartEnd {
public DateTime Start { get; set; }
public DateTime Stop { get; set; }
}
// Some data to test :)
var testData = new[] {
new Course() {
Day = "Sunday",
StartTime = DateTime.Parse("01-01-2000 08:20:00"),
EndTime = DateTime.Parse("01-01-2000 10:20:00")
},
new Course() {
Day = "Saturday",
StartTime = DateTime.Parse("01-01-2000 11:00:00"),
EndTime = DateTime.Parse("01-01-2000 14:00:00")
},
new Course() {
Day = "Monday",
StartTime = DateTime.Parse("01-01-2000 18:20:00"),
EndTime = DateTime.Parse("01-01-2000 21:20:00")
},
new Course() {
Day = "Saturday",
StartTime = DateTime.Parse("01-01-2000 20:00:00"),
EndTime = DateTime.Parse("01-01-2000 22:00:00")
},
};
// The actual data processing
var jsonData = testData
.GroupBy(x => x.Day, x => new StartEnd() { Start = x.StartTime, Stop = x.EndTime }) // Convert to output type while grouping
.ToDictionary(x => x.Key, x => x.ToArray()); // Convert to dictionary, iterating IEnumerables creates by GroupBy
答案 1 :(得分:1)
试试这个
[HttpGet]
public JsonResult GetTime()
{
var data = _db.CourseTimes
.GroupBy(c => c.Day)
.ToDictionary(g => g.Key, v => v.Select(c => new { start = c.StartTime, stop = c.EndTime }));
return Json(data, JsonRequestBehavior.AllowGet);
}
按天分组并使用字典作为关键字来获取您想要的预期格式。