如何构建JSON结果C#,MVC?

时间:2016-10-20 21:30:37

标签: c# json asp.net-mvc json.net asp.net-mvc-5

我有这个数据

data

并希望像

一样返回

json

我写了这段代码

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

2 个答案:

答案 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);
}

按天分组并使用字典作为关键字来获取您想要的预期格式。