【问题标题】:Convert c# list of objects to JSON将 c# 对象列表转换为 JSON
【发布时间】:2017-03-28 10:19:30
【问题描述】:

如何将 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();
}

在视图中,我尝试使用以下代码在警报框中打印 json:

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

但我得到了空的警报框。

这里有什么问题?

【问题讨论】:

  • holidaysResult != holidayJson
  • 我刚刚更改了它,但我仍然收到一个空警报框
  • 不调用Json 只是返回一个JsonResult instance?这真的是你想要的吗?
  • 小提示:使用console.log而不是alerts,这样你就可以在你得到的结果中导航

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


【解决方案1】:

您可以简单地将模型传回查看,然后使用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>

【讨论】:

    【解决方案2】:

    你可以使用jsonconvert.serializeobject方法。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-06
      • 1970-01-01
      • 1970-01-01
      • 2014-04-07
      相关资源
      最近更新 更多