Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用JSON.NET向数组添加自定义名称_C#_Arrays_List_Datatable_Json.net - Fatal编程技术网

C# 使用JSON.NET向数组添加自定义名称

C# 使用JSON.NET向数组添加自定义名称,c#,arrays,list,datatable,json.net,C#,Arrays,List,Datatable,Json.net,我需要检索JSON对象的数组,如下所示: { "MyCustomName": [ { "id": 0, "item": "item 0" }, { "id": 1, "item": "item 1" } ] } 与此相反: { [ { "id": 0, "item": "item 0" }, { "id": 1, "item": "item 1" } ] } 以下是我使用的代码: using (SqlConnection con = conection.Conect())

我需要检索JSON对象的数组,如下所示:

{ "MyCustomName": [ { "id": 0, "item": "item 0" }, { "id": 1, "item": "item 1" } ] }
与此相反:

{ [ { "id": 0, "item": "item 0" }, { "id": 1, "item": "item 1" } ] }
以下是我使用的代码:

    using (SqlConnection con = conection.Conect())
            {
                using (SqlCommand cmd = new SqlCommand("SelPeople", con))
                {
                    con.Open();
                    cmd.CommandType = CommandType.StoredProcedure;
                    using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                    {
                        DataTable dt = new DataTable("MyCustomName");  
                        sda.Fill(dt);
                        List<Personal> ListOfPeople= new List<Personal>();

                        foreach (DataRow dr in dt.Rows)
                        {
                            Personal persona = new Personal();

                            persona.Id = Convert.ToInt32(dr["Id"].ToString());
                        persona.Name = dr["Name"].ToString();
                        //add one row to the list
                        ListOfPeople.Add(persona);
                    }

                   JsonConvert.SerializeObject(ListOfPeople, Formatting.Indented);
                    Response.Write(json);
                }
            }
        }
使用(SqlConnection con=conconnection.Conect())
{
使用(SqlCommand cmd=newsqlcommand(“selpeomen”,con))
{
con.Open();
cmd.CommandType=CommandType.storedProcess;
使用(SqlDataAdapter sda=newsqldataadapter(cmd))
{
DataTable dt=新的DataTable(“MyCustomName”);
sda.填充(dt);
List ListOfPeople=新列表();
foreach(数据行dr在dt.行中)
{
个人角色=新的个人角色();
persona.Id=Convert.ToInt32(dr[“Id”].ToString());
persona.Name=dr[“Name”].ToString();
//在列表中添加一行
人物列表。添加(人物角色);
}
SerializeObject(ListOfPeople,Formatting.Indented);
Response.Write(json);
}
}
}
一些帮助会很好,谢谢:)

看看这篇文章

在控制器中更改此部分

JsonConvert.SerializeObject(ListOfPeople, Formatting.Indented);
Response.Write(json);
致:

string json = JsonConvert.SerializeObject(new
{
    MyCustomName = ListadoDePersonal;
});
Response.Write(json);