From DataTable in C# .NET to JSON

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

    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

    0 讨论(0)
提交回复
热议问题