在 C# 中将 SqlDataReader 列值转换为 json 字符串

Kel*_*use 2 .net c# asp.net ado.net json

我想根据 SQLDataReader 读取的输出输出一个字符串(或者可能是其他变量类型,如果字符串不理想)。我一直在玩“while”循环, while (reader.Read())

我需要得到一些可以用 json.net 序列化的东西。

这是我当前的代码 - 它输出到调试日志只是为了确保我成功地从数据库读取。

protected void Page_Load(object sender, EventArgs e)
    {

        string connectionString = "Data Source =.\\SQLEXPRESS; Initial Catalog = TeamProject; Integrated Security = True; MultipleActiveResultSets = True";

        string querystring = "RosterMake";

        using (SqlConnection connection = 
            new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand(querystring, connection);
            command.CommandType = CommandType.StoredProcedure;

            try
            {
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {
                    System.Diagnostics.Debug.WriteLine("\t{0}\t{1}\t{2}",
                    reader[0], reader[1], reader[2]);

                    //  What do I put here to make the results something I can 
                    //  serialize with json.net???

                }
                reader.Close();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("oops");
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Fel*_*ani 6

您可以使用 aList<Dictionary<string, object>>来保存值并将其序列化。会将其Newtonsoft.Json序列化为简单的 json。请参阅代码示例和注释:

// define the list
var values = new List<Dictionary<string, object>>();
try
{
    connection.Open();
    // Use the using block to make sure you are disposing the dataReader object.
    using (SqlDataReader reader = command.ExecuteReader())
    {
        do
        {               
            while (reader.Read())
            {
                // define the dictionary
                var fieldValues = new Dictionary<string, object>();

                // fill up each column and values on the dictionary                 
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    fieldValues.Add(reader.GetName(i), reader[i]);
                }

                // add the dictionary on the values list
                values.Add(fieldValues);

            }
        } while (reader.NextResult());   // if you have multiple result sets on the Stored Procedure, use this. Otherwise you could remove the do/while loop and use just the while.
    }
}
catch (Exception ex)
{
    System.Diagnostics.Debug.WriteLine("oops");
}
Run Code Online (Sandbox Code Playgroud)

现在你可以序列化values使用JsonConvert.Serialize(values),你将得到它作为 json 如下:

[
    {
        "Name": "John", Age: 30, Sex: "M"
    },
    {
        "Name": "Maria", Age: 28, Sex: "F"
    }
]
Run Code Online (Sandbox Code Playgroud)


小智 5

将 SqlDataReader 转换为 JSON 很简单。需要的是 Newtonsoft.Json;库这是示例

            SqlDataReader rdr = cmd.ExecuteReader();
            //sqlDatoToJson(rdr);
            var datatable = new DataTable();
            datatable.Load(rdr);
            string JsonResponse = string.Empty;
            JsonResponse = JsonConvert.SerializeObject(datatable);
            System.Diagnostics.Debug.WriteLine("3");
            System.Diagnostics.Debug.WriteLine(rdr);
            con.Close();
            return new JsonResult() { Data = JsonResponse,JsonRequestBehavior = JsonRequestBehavior.AllowGet };
Run Code Online (Sandbox Code Playgroud)