From DataTable in C# .NET to JSON

前端 未结 7 658
一整个雨季
一整个雨季 2020-12-04 18:12

I am pretty new at C# and .NET, but I\'ve made this code to call a stored procedure, and I then want to take the returned DataTable and convert it to JSON.

         


        
7条回答
  •  感情败类
    2020-12-04 19:09

    Although the JavaScriptSerializer (System.Web.Script.Serialization.JavaScriptSerializer) cannot convert a DataTable directly into JSON, it is possible to unpack a DataTable into a List that may then be serialized.

    The following function converts an arbitrary DataTable into a JSON string (without prior knowledge about field names or data types):

    public static string DataTableToJSON(DataTable table)
    {
        var list = new List>();
    
        foreach (DataRow row in table.Rows)
        {
            var dict = new Dictionary();
    
            foreach (DataColumn col in table.Columns)
            {
                dict[col.ColumnName] = row[col];
            }
            list.Add(dict);
        }
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        return serializer.Serialize(list);
    }
    

提交回复
热议问题