使用JSON.NET将自定义名称添加到数组中。

19 浏览
0 Comments

使用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 ListOfPeople= new List();
                        foreach (DataRow dr in dt.Rows)
                        {
                            Personal persona = new Personal();
                            persona.Id = Convert.ToInt32(dr["Id"].ToString());
                        persona.Name = dr["Name"].ToString();
                        //将一行添加到列表中
                        ListOfPeople.Add(persona);
                    }
                   JsonConvert.SerializeObject(ListOfPeople, Formatting.Indented);
                    Response.Write(json);
                }
            }
        }

希望能得到一些帮助,谢谢 🙂

0
0 Comments

问题原因:原来的代码中,使用了JSON.NET将一个数组序列化为JSON字符串,并通过Response.Write方法将其输出。然而,输出的JSON字符串中没有自定义的名称。

解决方法:修改代码,使用JSON.NET的SerializeObject方法将一个匿名对象序列化为JSON字符串,并在该匿名对象中添加自定义的名称。然后,通过Response.Write方法将该JSON字符串输出。

以下是修改后的代码:

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

通过以上修改,输出的JSON字符串中将包含自定义的名称"MyCustomName"。

0