c# - 使用 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())
            {
                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);
                }
            }
        }

一些帮助会很好,谢谢:)

最佳答案

看看这篇文章from another user

在你的 Controller 中更改这部分

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

致:

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

关于c# - 使用 JSON.NET 将自定义名称添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31529296/

相关文章:

c# - MvxSidebarPresentationAttribute 未在演示者字典中配置

javascript - 为什么在 javascript 中分配给字符串的一部分(使用数组语法)不会引发错误?

c++ - 重载后缀增量运算符

c - 如何组合两个数组以在 C 中创建一个更大的数组

python - Networkx:计算和存储图形上到 Pandas 数据框的最短路径

c# - 为什么我需要一个中间转换来从 struct 到 decimal,而不是 struct 到 int?

c# - Odbc 连接字符串导致登录失败

c# - 未知的鉴别器值 C# Mongo

python - 尝试创建一个包含从 infile 到 outfile 的数字的列表

python - 在 python 中迭代和更新列表