From DataTable in C# .NET to JSON
Asked Answered
C

7

14

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.

    SqlConnection con = new SqlConnection("connection string here");
    SqlDataAdapter da = new SqlDataAdapter();
    SqlCommand cmd = new SqlCommand("getDates", con);
    SqlParameter par = new SqlParameter("@PlaceID", SqlDbType.Int);
    par.Value = 42;
    da.SelectCommand = cmd;
    cmd.Parameters.Add(par);
    DataSet ds = new DataSet();
    DataTable dt = new DataTable();

    con.Open();

    try{
        cmd.CommandType = CommandType.StoredProcedure;
        da.Fill(ds);
    }

My question then is what is the best/simplest way to do that? An example would be great as I'm still very new to this.

Charleen answered 22/2, 2010 at 18:5 Comment(1)
possible duplicate of how to convert datatable to json in C#Ocko
C
7

Instead of a datatable you should use a datareader. Your code is inefficient and somewhat hard to read - you may want to do something like this:

StringBuilder json = new StringBuilder();

using(SqlConnection cnn = new SqlConnection(your_connection_string)) 
{
    cnn.open();

    using(SqlCommand cmd = new SqlCommand("name_of_stored_procedure", cnn)) 
    {
        cmd.Paramters.AddWithValue("@Param", "value");

        using(SqlDataReader reader = cmd.ExecuteReader()) 
        {
            while(reader.Read()) 
            {
                json.AppendFormat("{{\"name\": \"{0}\"}}", reader["name"]);
            }
        }
    }

    cnn.close();
} 

you can then use json.ToString to get the outpt

Currant answered 22/2, 2010 at 18:16 Comment(2)
Thank you, and thank you for the comment on my code. I will try to clean it up. I'll attempt this and see what I can make of it :]Charleen
and scape chars? and arrays? its not real json :-/Glossary
S
23

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);
}
Semester answered 21/8, 2012 at 21:10 Comment(0)
D
14

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"]
}
Derrick answered 28/3, 2013 at 2:39 Comment(0)
C
7

Instead of a datatable you should use a datareader. Your code is inefficient and somewhat hard to read - you may want to do something like this:

StringBuilder json = new StringBuilder();

using(SqlConnection cnn = new SqlConnection(your_connection_string)) 
{
    cnn.open();

    using(SqlCommand cmd = new SqlCommand("name_of_stored_procedure", cnn)) 
    {
        cmd.Paramters.AddWithValue("@Param", "value");

        using(SqlDataReader reader = cmd.ExecuteReader()) 
        {
            while(reader.Read()) 
            {
                json.AppendFormat("{{\"name\": \"{0}\"}}", reader["name"]);
            }
        }
    }

    cnn.close();
} 

you can then use json.ToString to get the outpt

Currant answered 22/2, 2010 at 18:16 Comment(2)
Thank you, and thank you for the comment on my code. I will try to clean it up. I'll attempt this and see what I can make of it :]Charleen
and scape chars? and arrays? its not real json :-/Glossary
F
7

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();
}
Fabriane answered 23/1, 2012 at 0:3 Comment(1)
@user1243068 This answer is pretty old. Today I'd probably just push the dataReader's contents into a List<Foo> and use JSON.NET (aka. Newtonsoft) to turn the list into a JSON array.Currant
T
3

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);
}
Torpor answered 27/5, 2013 at 11:23 Comment(0)
V
3

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]", "");
            }
Velvavelvet answered 11/1, 2014 at 13:25 Comment(0)
A
2

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()
);
Asexual answered 23/1, 2016 at 9:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.