Search code examples
c#.netjsondatatablejavascriptserializer

From DataTable in C# .NET to JSON


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.


Solution

  • 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