【问题标题】:Formatting JSON as an Array in ASP.NET MVC在 ASP.NET MVC 中将 JSON 格式化为数组
【发布时间】:2018-04-26 20:37:38
【问题描述】:

我很难将格式化的JSON 作为数组返回。我当前的代码已经将JSON 作为数组返回,但我想先去掉这些括号[] 以获得我想要的输出。

控制器

public JsonResult GenerateGanttChart()
    {
        SPMS_GanttChartLayers ddl = new SPMS_GanttChartLayers();
        var data = ddl.GenerateGanttChart();
        return Json(data, JsonRequestBehavior.AllowGet);
    }

图层

public IEnumerable<SPMS_GanttChartRootModel> GenerateGanttChart()
    {
        List<SPMS_GanttChartModel> child_data = new List<SPMS_GanttChartModel>();
        {
            using (SqlConnection con = new SqlConnection(Conn.MyConn()))
            {
                SqlCommand com = new SqlCommand("dbo.sp_SPMS_GanttChart 7078, 1", con);
                con.Open();
                SqlDataReader reader = com.ExecuteReader();
                while (reader.Read())
                {
                    SPMS_GanttChartModel value = new SPMS_GanttChartModel();
                    value.id = Convert.ToInt32(reader.GetValue(0));
                    value.start_date = Convert.ToString(reader.GetValue(1));
                    value.duration = Convert.ToInt32(reader.GetValue(2));
                    value.text = Convert.ToString(reader.GetValue(3));
                    child_data.Add(value);
                }
            }

        }
        List<SPMS_GanttChartRootModel> array = new List<SPMS_GanttChartRootModel>();
        {
            SPMS_GanttChartRootModel value = new SPMS_GanttChartRootModel();
            value.data = child_data;
            array.Add(value);
        };
        return array;
    }

电流输出

[{
"data": [{
    "id": 1,
    "start_date": "11/07/2017 08:00:00 AM",
    "duration": 23,
    "text": "Project #1"
}, ... ]
}]

期望的输出

{
"data": [{
    "id": 1,
    "start_date": "11/07/2017 08:00:00 AM",
    "duration": 23,
    "text": "Project #1"
}, ... ]
}

【问题讨论】:

  • 您目前如何返回 JSON? yoyu 分享的代码没有返回任何 Json 响应。这是 asp.net web api 控制器吗?
  • @Shyju 我编辑了我的帖子。检查它是否回答了您的问题。

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


【解决方案1】:

目前,您正在从您的 GenerateGanttChart 方法返回一个 List&lt;SPMS_GanttChartRootModel&gt;

返回SPMS_GanttChartRootModel 对象。

SPMS_GanttChartRootModel value = new SPMS_GanttChartRootModel();
value.data = child_data;
return value;

还要确保你的方法的返回类型现在是SPMS_GanttChartRootModel

public SPMS_GanttChartRootModel  GenerateGanttChart()
{
    var child_data = new List<SPMS_GanttChartModel>();
    {
        //your existing code to populate this collection
    };

     var value = new SPMS_GanttChartRootModel();
     value.data = child_data;
     return value;
}

在您的操作方法中,将此单个对象传递给Json 方法

public JsonResult GenerateGanttChart()
{
    var ddl = new SPMS_GanttChartLayers();
    var data = ddl.GenerateGanttChart();
    return Json(data, JsonRequestBehavior.AllowGet);
}

【讨论】:

  • 完美。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-04
  • 2012-09-23
  • 2020-11-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多