From DataTable in C# .NET to JSON

前端 未结 7 628
一整个雨季
一整个雨季 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 18:54

    I use JavaScriptSerializer + LINQ

    return new JavaScriptSerializer().Serialize(
      dataTable.Rows.Cast<DataRow>()
      .Select(row => row.Table.Columns.Cast<DataColumn>()
        .ToDictionary(col => col.ColumnName, col => row[col.ColumnName]))
      .ToList()
    );
    
    0 讨论(0)
  • 2020-12-04 19:06

    Thanks Ariel. Your answer was very helpful. Here is a version that builds on your answer.

    public string ReadToJson(SqlDataReader reader)
    {
      List<string> cols = new List<string>(10);
      int ncols = reader.FieldCount;
      for (int i = 0; i < ncols; ++i)
      {
        cols.Add(reader.GetName(i));
      }
      StringBuilder sbJson = new StringBuilder("[");
      //process each row
      while (reader.Read())
      {
        sbJson.Append("{");
        foreach (string col in cols)
        {
          sbJson.AppendFormat("\"{0}\":{1}, ", col, reader[col]);
        }
        sbJson.Replace(", ", "},", sbJson.Length - 2, 2);
      }
      sbJson.Replace("},", "}]", sbJson.Length - 2, 2);
      return sbJson.ToString();
    }
    
    0 讨论(0)
  • 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<Dictionary<string, object>>();
    
        foreach (DataRow row in table.Rows)
        {
            var dict = new Dictionary<string, object>();
    
            foreach (DataColumn col in table.Columns)
            {
                dict[col.ColumnName] = row[col];
            }
            list.Add(dict);
        }
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        return serializer.Serialize(list);
    }
    
    0 讨论(0)
  • 2020-12-04 19:11

    You could use the JSON.NET library: http://json.codeplex.com/ to serialize/deserialize the DataTable.

    string json = JsonConvert.SerializeObject(table);
    

    which serializes to something like this:

    [ { "Column1": "Row Value", "Column2": "2" } ]
    

    If you need to serialize more info about the DataTable e.g. column schema, primary key, table name then you could use the custom converter I wrote: https://github.com/chris-herring/DataTableConverter. Use it like this:

    string json = JsonConvert.SerializeObject(table, new Serialization.DataTableConverter());
    DataTable table = JsonConvert.DeserializeObject<DataTable>(json, new Serialization.DataTableConverter());
    

    which serializes to something like this:

    {
        "TableName": "TestTable",
        "Columns": [
            {
                "AllowDBNull": false,
                "AutoIncrement": true,
                "AutoIncrementSeed": 2,
                "AutoIncrementStep": 1,
                "Caption": "PrimaryKey",
                "ColumnName": "PrimaryKey",
                "DataType": "Int32",
                "DateTimeMode": "UnspecifiedLocal",
                "DefaultValue": null,
                "MaxLength": -1,
                "Ordinal": 0,
                "ReadOnly": false,
                "Unique": true
            }
        ],
        "Rows": [
            [
                1
            ],
            [
                2
            ],
            [
                3
            ]
        ],
        "PrimaryKey": ["PrimaryKey"]
    }
    
    0 讨论(0)
  • 2020-12-04 19:14

    Thank you Karl Wenzel. I had a problem where I could only receive data table from an old asmx webservice. Now I wrote a web page which can parse this DataTable and return it in JSON.

    public static string DataTableToJSON(DataTable table)
    {
        List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
    
        foreach (DataRow row in table.Rows)
        {
            Dictionary<string, object> dict = new Dictionary<string, object>();
    
            foreach (DataColumn col in table.Columns)
            {
                dict[col.ColumnName] = row[col];
            }
            list.Add(dict);
        }
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        return serializer.Serialize(list);
    }
    
    0 讨论(0)
  • 2020-12-04 19:17

    An alternative way without using javascript serializer:

    public static string DataTableToJSON(DataTable Dt)
                {
                    string[] StrDc = new string[Dt.Columns.Count];
    
                    string HeadStr = string.Empty;
                    for (int i = 0; i < Dt.Columns.Count; i++)
                    {
    
                        StrDc[i] = Dt.Columns[i].Caption;
                        HeadStr += "\"" + StrDc[i] + "\":\"" + StrDc[i] + i.ToString() + "¾" + "\",";
    
                    }
    
                    HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
    
                    StringBuilder Sb = new StringBuilder();
    
                    Sb.Append("[");
    
                    for (int i = 0; i < Dt.Rows.Count; i++)
                    {
    
                        string TempStr = HeadStr;
    
                        for (int j = 0; j < Dt.Columns.Count; j++)
                        {
    
                            TempStr = TempStr.Replace(Dt.Columns[j] + j.ToString() + "¾", Dt.Rows[i][j].ToString().Trim());
                        }
                        //Sb.AppendFormat("{{{0}}},",TempStr);
    
                        Sb.Append("{"+TempStr + "},");
                    }
    
                    Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
    
                    if(Sb.ToString().Length>0)
                    Sb.Append("]");
    
                    return StripControlChars(Sb.ToString());
    
                } 
     //Function to strip control characters:
    
    //A character that does not represent a printable character  but serves to initiate a particular action.
    
                public static string StripControlChars(string s)
                {
                    return Regex.Replace(s, @"[^\x20-\x7F]", "");
                }
    
    0 讨论(0)
提交回复
热议问题