从 C# .NET 中的 DataTable 到 JSON [英] From DataTable in C# .NET to JSON

查看:32
本文介绍了从 C# .NET 中的 DataTable 到 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 C# 和 .NET 还很陌生,但我已经编写了这段代码来调用存储过程,然后我想获取返回的 DataTable 并将其转换为 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.

推荐答案

您应该使用数据读取器而不是数据表.您的代码效率低下且难以阅读 - 您可能想要执行以下操作:

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();
} 

然后你可以使用 json.ToString 来获取输出

you can then use json.ToString to get the outpt

这篇关于从 C# .NET 中的 DataTable 到 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆