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

时间:2017-07-13 13:48:58

标签: c# .net json ado.net

我希望根据SQLDataReader读取的输出输出一个字符串(如果字符串不是理想的话,可能是其他变量类型)。我一直在玩#34;而#34;循环,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"); } } } }

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

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

{{1}}

提前致谢!

4 个答案:

答案 0 :(得分:2)

您可以使用List<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");
}

现在你可以使用values序列化JsonConvert.Serialize(values),你会得到像这样的json:

[
    {
        "Name": "John", Age: 30, Sex: "M"
    },
    {
        "Name": "Maria", Age: 28, Sex: "F"
    }
]

答案 1 :(得分:0)

只需使用GetString()上的SqlDataReader方法即可。你想要这样的东西:

string myString;

using (SqlDataReader rdr = command.ExecuteReader())
{
    do
    {
        while (rdr.Read())
        {
            myString = rdr.GetString(0);
        }
    } while (rdr.NextResult());
}

注意这只是盲目地读取字符串直到没有任何东西。由你来正确地设置逻辑。

答案 2 :(得分:0)

你可以返回一个清单:

 public List<EnEntity> methodname(string pParam1)
    {
        try
        {
            List<EnEntity> ListEntity = new List<EnEntity>();
            SqlCommand cmd = new SqlCommand("sp_name", conexion);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@vParam", SqlDbType.VarChar).Value = pParam1;

            SqlDataReader drd = cmd.ExecuteReader();

            if (drd.HasRows)//!=null
            {
                int pos_iIndex = drd.GetOrdinal("iColumnaName");
                while (drd.Read())
                {
                    EnEntity oEnEntity = new EnEntity();

                    oEnEntity.iPropertie = drd.IsDBNull(pos_iIndex) ? 0 : drd.GetInt32(pos_iIndex);

                    ListEnEntity.Add(oEnEntity);
                }
                drd.Close();

            }
            return (ListEnEntity);
        }
        catch (Exception ex)
        {                
            throw ex;
        }
    }

答案 3 :(得分:0)

将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 };