将c#对象列表转换为JSON

时间:2017-03-28 10:19:30

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

如何将c#对象解析为JSON?

这是我得到的代码:

型号:

namespace MvcApplication1.Models
{
    public class HolidayModel
    {
        public int HolidayID { get; set; }
        public string HolidayDescription { get; set; }
        public string HolidayStartDate { get; set; }
        public string HolidayEndDate { get; set; }
        public int Count { get; set; }
        public string HolidayOld { get; set; }
        public string HolidayNew { get; set; }
        public int EmployeeID { get; set; }
        public int HolidaySelectedYear { get; set; }

        public int StartDay { get; set; }
        public int StartMonth { get; set; }
        public int StartYear { get; set; }

        public int EndDay { get; set; }
        public int EndMonth { get; set; }
        public int EndYear { get; set; }
    }
}

控制器:

public ActionResult GetEvents()
{
    List<Holiday> holidays = conn.Holidays.ToList();

    ViewBag.holidaysJson = Json(holidays, JsonRequestBehavior.AllowGet);
    return View();
}

在View中我尝试使用以下代码在警告框中打印json:

<script>
    alert("@ViewBag.holidaysJson");
</script>

但是我得到空警报框。

这里有什么问题?

2 个答案:

答案 0 :(得分:3)

您只需将模型传回视图,然后使用Json.Encode方法将其转换为JSON:

控制器代码为:

public ActionResult GetEvents()
{
    List<Holiday> holidays = conn.Holidays.ToList(); 
    return View(holidays); 
}

并在视野中:

@model List<Holiday>
<script>
    var holidaysJson = @Html.Raw(Json.Encode(Model)); // json object
    alert(JSON.stringify(holidaysJson)); // converting it to string representation
</script>

答案 1 :(得分:0)

您可以使用jsonconvert.serializeobject方法。

public ActionResult GetEvents()
{
    List<Holiday> holidays = conn.Holidays.ToList();
    ViewBag.holidaysResult = JsonConvert.SerializeObject(holidays);
    return View(holidays);
}